/// <summary> /// 执行 /// </summary> /// <param name="args">实际参数</param> /// <returns></returns> public override VarData Run(VarData[] args) { // 变量表-添加形参(从类型信息中获取形参信息:) VarTable.Add(new VarEntry { Data = new VarData { } }); // 变量表-保存实参 VarTable.Add(new VarEntry { Name = "argumnets", //Raw = "argumnets", Data = new VarData { Sign = new SignInfo { IsUnit = true, Name = "List<Object>" } } }); // 计算 // 返回值 return(new VarData { }); }
public void Generate(List <FourExp> fourExpList, VarTable varTable, List <AssemblerIns> cmdList) { //为变量分配内存,并对符号的活跃信息域进行初始化 List <string> varNameList = varTable.GetNames(); initVarTable(varTable, fourExpList, varNameList); //生成数据段 genDataIns(varNameList, varTable, cmdList); int count = 0; foreach (FourExp f in fourExpList) { foreach (string varName in varNameList) { //从符号表的后续引用信息域和活跃域中去除无用信息 if (varTable.GetPeekRefeInfo(varName) == count) { //varTable.PopRefeInfo(varName); varTable.PopActInfo(varName); } count++; } convert(f, varTable, cmdList); optimize(); } }
public void PersistentVarFileInfo() { // Prepare mock data. var versionInfo = new VersionInfoResource(); var varFileInfo = new VarFileInfo(); var table = new VarTable(); for (ushort i = 0; i < 10; i++) { table.Values.Add(i); } varFileInfo.Tables.Add(table); versionInfo.AddEntry(varFileInfo); // Serialize. var tempStream = new MemoryStream(); versionInfo.Write(new BinaryStreamWriter(tempStream)); // Reload. var newVersionInfo = VersionInfoResource.FromReader(new ByteArrayReader(tempStream.ToArray())); // Verify. var newVarFileInfo = newVersionInfo.GetChild <VarFileInfo>(VarFileInfo.VarFileInfoKey); Assert.NotNull(newVarFileInfo); Assert.Single(newVarFileInfo.Tables); var newTable = newVarFileInfo.Tables[0]; Assert.Equal(table.Values, newTable.Values); }
//TODO TESTS private static void Command(ListController <TokenModel> lc) { var beg = lc.GetNext(); if (TypesTools.IsType(beg.Text)) { lc.SetBack(); Initialization(lc); } else if (VarTable.Contains(beg.Text)) { lc.SetBack(); var node = VariableAssign(lc); Commands.Add(node); } else if (FuncTable.Contains(beg.Text)) { lc.SetBack(); var node = FuncExecute(lc); Commands.Add(node); } else { throw new ParseException($"Cannot resolve '{beg.Text}'", beg); } //todo lately var = Arithmetic Expression //todo more lately type func }
public void TestDeepCopyBytes() { string filename = Path.Combine(Environment.SystemDirectory, "atl.dll"); Assert.IsTrue(File.Exists(filename)); VersionResource existingVersionResource = new VersionResource(); existingVersionResource.Language = ResourceUtil.USENGLISHLANGID; Console.WriteLine("Loading {0}", filename); existingVersionResource.LoadFrom(filename); DumpResource.Dump(existingVersionResource); VersionResource versionResource = new VersionResource(); versionResource.FileVersion = existingVersionResource.FileVersion; versionResource.ProductVersion = existingVersionResource.ProductVersion; StringFileInfo existingVersionResourceStringFileInfo = (StringFileInfo)existingVersionResource["StringFileInfo"]; VarFileInfo existingVersionResourceVarFileInfo = (VarFileInfo)existingVersionResource["VarFileInfo"]; // copy string resources, data only StringFileInfo stringFileInfo = new StringFileInfo(); versionResource["StringFileInfo"] = stringFileInfo; { Dictionary <string, StringTable> .Enumerator enumerator = existingVersionResourceStringFileInfo.Strings.GetEnumerator(); while (enumerator.MoveNext()) { StringTable stringTable = new StringTable(enumerator.Current.Key); stringFileInfo.Strings.Add(enumerator.Current.Key, stringTable); Dictionary <string, StringTableEntry> .Enumerator resourceEnumerator = enumerator.Current.Value.Strings.GetEnumerator(); while (resourceEnumerator.MoveNext()) { StringTableEntry stringResource = new StringTableEntry(resourceEnumerator.Current.Key); stringResource.Value = resourceEnumerator.Current.Value.Value; stringTable.Strings.Add(resourceEnumerator.Current.Key, stringResource); } } } // copy var resources, data only VarFileInfo varFileInfo = new VarFileInfo(); versionResource["VarFileInfo"] = varFileInfo; { Dictionary <string, VarTable> .Enumerator enumerator = existingVersionResourceVarFileInfo.Vars.GetEnumerator(); while (enumerator.MoveNext()) { VarTable varTable = new VarTable(enumerator.Current.Key); varFileInfo.Vars.Add(enumerator.Current.Key, varTable); Dictionary <UInt16, UInt16> .Enumerator translationEnumerator = enumerator.Current.Value.Languages.GetEnumerator(); while (translationEnumerator.MoveNext()) { varTable.Languages.Add(translationEnumerator.Current.Key, translationEnumerator.Current.Value); } } } ByteUtils.CompareBytes(existingVersionResource.WriteAndGetBytes(), versionResource.WriteAndGetBytes()); }
static void Main(string[] args) { var KeyWords = new ConstTable(@"Tables/KeyWords.txt"); var Delimiters = new ConstTable(@"Tables/Delimiters.txt"); var Operations = new ConstTable(@"Tables/Operations.txt"); var Constants = new VarTable(); var Identifiers = new VarTable(); var Goto = new ConstTable(@"Tables/Goto.txt"); var Labels = new VarTable(); string TestFile = "test3"; LexicAnalyzer LA = new LexicAnalyzer(KeyWords, Delimiters, Operations, Constants, Identifiers); Token[] LexicAnalysisResult = LA.AnalyzeSource(TestFile); SyntacticAnalyzer SA = new SyntacticAnalyzer(KeyWords, Delimiters, Operations, Constants, Identifiers, Goto, Labels); try { SA.AnalyzeTokens(LexicAnalysisResult); Console.WriteLine("Синтаксическтй анализ успешно завершен."); } catch (Exception Ex) { Console.WriteLine("Ошибка: " + Ex.Message); File.WriteAllText(Directory.GetCurrentDirectory() + @"\" + TestFile + ".syn.out.txt", "Ошибка: " + Ex.Message); } CodeBuilder CB = new CodeBuilder(KeyWords, Operations, Constants, Identifiers, Goto, Labels); CB.BuildCode(SA.Output); File.WriteAllText(Directory.GetCurrentDirectory() + @"\" + TestFile + ".asm", CB.ToString()); Console.WriteLine($"Построение кода успешно завершено. Выходной файл: {TestFile}.asm"); }
public void TestDeleteAndSaveVersionResource(string binaryName, int language) { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "testDeleteAndSaveVersionResource.dll"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); VersionResource existingVersionResource = new VersionResource(); existingVersionResource.Language = (ushort)language; existingVersionResource.DeleteFrom(targetFilename); VersionResource versionResource = new VersionResource(); versionResource.FileVersion = "1.2.3.4"; versionResource.ProductVersion = "4.5.6.7"; StringFileInfo stringFileInfo = new StringFileInfo(); versionResource[stringFileInfo.Key] = stringFileInfo; StringTable stringFileInfoStrings = new StringTable(); // "040904b0" stringFileInfoStrings.LanguageID = (ushort)language; stringFileInfoStrings.CodePage = 1200; Assert.AreEqual(language, stringFileInfoStrings.LanguageID); Assert.AreEqual(1200, stringFileInfoStrings.CodePage); stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings); stringFileInfoStrings["ProductName"] = "ResourceLib"; stringFileInfoStrings["FileDescription"] = "File updated by ResourceLib\0"; stringFileInfoStrings["CompanyName"] = "Vestris Inc."; stringFileInfoStrings["LegalCopyright"] = "All Rights Reserved\0"; stringFileInfoStrings["EmptyValue"] = ""; stringFileInfoStrings["Comments"] = string.Format("{0}\0", Guid.NewGuid()); stringFileInfoStrings["ProductVersion"] = string.Format("{0}\0", versionResource.ProductVersion); VarFileInfo varFileInfo = new VarFileInfo(); versionResource[varFileInfo.Key] = varFileInfo; VarTable varFileInfoTranslation = new VarTable("Translation"); varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation); varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300; versionResource.SaveTo(targetFilename); Console.WriteLine("Reloading {0}", targetFilename); VersionResource newVersionResource = new VersionResource(); newVersionResource.LoadFrom(targetFilename); DumpResource.Dump(newVersionResource); AssertOneVersionResource(targetFilename); Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion); Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion); }
public LexicAnalyzer( ConstTable KeyWords, ConstTable Delimiters, ConstTable Operations, VarTable Constants, VarTable Identifiers) { FSM = new FiniteStateMachine(KeyWords, Delimiters, Operations, Constants, Identifiers); }
/// <summary> /// 调整变量表和寄存器表中的相关域 /// </summary> /// <param name="regName">计算器名</param> /// <param name="varTable">变量表</param> /// <param name="cmdList">汇编指令列表</param> private void doAdjust(string regName, VarTable varTable, List <AssemblerIns> cmdList) { foreach (string varName in regUseTable.GetContent(regName)) { cmdList.Add(AssemblerFac.GenSW(regName, varTable.GetAddr(varName).ToString(), "$ZERO")); varTable.SetAddrInfo(varName, ""); } regUseTable.Clear(regName); }
public override void Translate(VarTable varTable, LabelStack labelStack, List <FourExp> fourExpList) { string label = labelStack.NewLabel(); fourExpList.Add(FourExpFac.GenLabel(label)); statement.Translate(varTable, labelStack, fourExpList); string condition = expression.GetValue(varTable, labelStack, fourExpList); fourExpList.Add(FourExpFac.GenJne(condition, 0 + "", label)); }
public void TestDeleteAndSaveVersionResource() { string filename = Path.Combine(Environment.SystemDirectory, "atl.dll"); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "testDeleteAndSaveVersionResource.dll"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); VersionResource existingVersionResource = new VersionResource(); existingVersionResource.DeleteFrom(targetFilename); VersionResource versionResource = new VersionResource(); versionResource.FileVersion = "1.2.3.4"; versionResource.ProductVersion = "4.5.6.7"; StringFileInfo stringFileInfo = new StringFileInfo(); versionResource[stringFileInfo.Key] = stringFileInfo; StringTable stringFileInfoStrings = new StringTable(); // "040904b0" stringFileInfoStrings.LanguageID = 1033; stringFileInfoStrings.CodePage = 1200; Assert.AreEqual(1033, stringFileInfoStrings.LanguageID); Assert.AreEqual(1200, stringFileInfoStrings.CodePage); stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings); stringFileInfoStrings["ProductName"] = "ResourceLib"; stringFileInfoStrings["FileDescription"] = "File updated by ResourceLib\0"; stringFileInfoStrings["CompanyName"] = "Vestris Inc."; stringFileInfoStrings["LegalCopyright"] = "All Rights Reserved\0"; stringFileInfoStrings["EmptyValue"] = ""; stringFileInfoStrings["Comments"] = string.Format("{0}\0", Guid.NewGuid()); stringFileInfoStrings["ProductVersion"] = string.Format("{0}\0", versionResource.ProductVersion); VarFileInfo varFileInfo = new VarFileInfo(); versionResource[varFileInfo.Key] = varFileInfo; VarTable varFileInfoTranslation = new VarTable("Translation"); varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation); varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300; versionResource.SaveTo(targetFilename); Console.WriteLine("Reloading {0}", targetFilename); VersionResource newVersionResource = new VersionResource(); newVersionResource.LoadFrom(targetFilename); DumpResource.Dump(newVersionResource); Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion); Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion); }
/// <summary> /// 遍历Ast树,生成四元式列表 /// </summary> /// <param name="ast">Ast树</param> /// <param name="varTable">变量表</param> /// <returns></returns> public static List <FourExp> Translate(Ast ast, VarTable varTable) { List <FourExp> fourExpList = new List <FourExp>(); LabelStack labelStack = new LabelStack(); foreach (Statement s in ast.Statements) { s.Translate(varTable, labelStack, fourExpList); } return(fourExpList); }
//TODO TESTS private static FunctionNode FuncExecute(ListController <TokenModel> lc) { var name = lc.GetNext(); CheckEqual(TryGetNext(lc, "( expected"), "(", "( expected"); var funcs = (List <FuncModel>)FuncTable.Funcs.Where(model => model.Name == name.Text); var args = new List <VarModel>(); var flag = true; var checkNext = TryGetNext(lc, ") or variable expected"); if (checkNext.Text == ")") { flag = false; lc.SetBack(); } while (flag) { var next = TryGetNext(lc, ") or variable expected"); if (VarTable.Contains(next.Text)) { args.Add(VarTable.Get(next.Text)); var afterVar = TryGetNext(lc, ") or , expected"); if (afterVar.Text == ",") { continue; } if (next.Text == ")") { lc.SetBack(); break; } } throw new ParseException($"Unexpected token {next.Text}", next); } var closingNest = lc.GetNext(); var suitableFunc = funcs.FirstOrDefault(model => model.ArgsType.Count == args.Count); if (suitableFunc == null) { throw new ParseException($"Cannot invoke function {name.Text} with {args.Count} arguments", name); } return(new FunctionNode { FuncName = suitableFunc, Args = args }); }
// ----------------------------------------------------- void ReplaceVersionInfo(Options options) { // Find version info resources ResourceInfo ri = new ResourceInfo(); ri.Load(options.outputExeFile); List <Resource> resources = ri.Resources[new ResourceId(Kernel32.ResourceTypes.RT_VERSION)]; ri.Dispose(); // Delete old version resource(s) from file foreach (Resource resource in resources) { resource.DeleteFrom(options.outputExeFile); } // Create new version info resource VersionResource versionResource = new VersionResource(); versionResource.FileVersion = options.versionInfo.fileVersion; versionResource.ProductVersion = options.versionInfo.productVersion; // Set all the info / strings StringFileInfo stringFileInfo = new StringFileInfo(); versionResource[stringFileInfo.Key] = stringFileInfo; StringTable stringFileInfoStrings = new StringTable(); stringFileInfoStrings.LanguageID = ResourceUtil.USENGLISHLANGID; stringFileInfoStrings.CodePage = 1200; stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings); // stringFileInfoStrings["ProductName"] = "not used"; stringFileInfoStrings["FileVersion"] = options.versionInfo.fileVersion; stringFileInfoStrings["FileDescription"] = options.versionInfo.productName; stringFileInfoStrings["LegalCopyright"] = options.versionInfo.legalCopyright; stringFileInfoStrings["CompanyName"] = options.versionInfo.companyName; // stringFileInfoStrings["Comments"] = "not used"; stringFileInfoStrings["ProductVersion"] = options.versionInfo.productVersion; // Don't really understand what this chunk does, but leaving it in anyway VarFileInfo varFileInfo = new VarFileInfo(); versionResource[varFileInfo.Key] = varFileInfo; VarTable varFileInfoTranslation = new VarTable("Translation"); varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation); varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300; // Save to file versionResource.SaveTo(options.outputExeFile); }
private static void Command(ListController <TokenModel> lc) { if (lc.TryGetNext(out var first)) { if (Keywords.Types.Contains(first.Text)) { var varType = first.Text; string varName = Variable(lc); VarTable.Add(varName, varType); } else if (VarTable.Contains(first.Text)) { if (!lc.TryGetNext(out var eq)) { throw new ParseException("= expected", lc.GetPrevious(), true); } if (eq.Text != "=") { throw new ParseException("= expected", lc.GetPrevious(), true); } AssingNode asNode = new AssingNode(); asNode.Left = new VarNode() { Variable = VarTable.Get(first.Text), }; if (!lc.TryGetNext(out var next)) { throw new ParseException("Function or expression expected", lc.GetPrevious(), true); } if (FuncTable.Contains(next.Text)) { lc.SetBack(); asNode.Right = Func(lc); } else if (VarTable.Contains(next.Text) || next.Text.All(c => Constants.Numbers.Contains(c))) { lc.SetBack(); //todo arithmetic throw new NotImplementedException("Arithmetic don't included, for now"); } else { throw new ParseException("Function or expression expected", lc.GetPrevious(), true); } } } }
public override bool Execute() { if (!Regex.IsMatch(FileVersion, @"\d+\.\d+.\d+\.\d+")) { Log.LogError("FileVersion value '{0}' is invalid - must be NNN.NNN.NNN.NNN (where N is any digit).", FileVersion); return(false); } if (!Regex.IsMatch(ProductVersion, @"\d+\.\d+\.\d+\.\d+")) { Log.LogError("ProductVersion value '{0}' is invalid - must be NNN.NNN.NNN.NNN (where N is any digit).", ProductVersion); return(false); } foreach (ITaskItem file in InputFiles) { string fileName = file.GetMetadata("FileName") + file.GetMetadata("Extension"); VersionResource resource = new VersionResource(); resource.FileVersion = FileVersion; resource.ProductVersion = ProductVersion; resource.FileFlags = 0; StringTable table = new StringTable(); table.LanguageID = 0x0409; table.CodePage = 0x04B0; table["CompanyName"] = CompanyName; table["FileDescription"] = FileDescription; table["FileVersion"] = FileVersion; table["InternalName"] = fileName; table["LegalCopyright"] = LegalCopyright; table["OriginalFilename"] = fileName; table["ProductName"] = ProductName; table["ProductVersion"] = ProductVersion; StringFileInfo stringInfo = new StringFileInfo(); stringInfo.Strings["040904B0"] = table; resource.Resources["StringFileInfo"] = stringInfo; VarTable varTable = new VarTable("Translation"); varTable.Languages[0x0409] = 0x04B0; VarFileInfo varInfo = new VarFileInfo(); varInfo.Vars["Translation"] = varTable; resource.Resources["VarFileInfo"] = varInfo; resource.SaveTo(file.GetMetadata("FullPath")); } return(true); }
/// <summary> /// Конструктор. /// </summary> public FiniteStateMachine() { State = States.Start; KeyWords = new ConstTable(@"Tables/KeyWords.txt"); Delimiters = new ConstTable(@"Tables/Delimiters.txt"); Operations = new ConstTable(@"Tables/Operations.txt"); Constants = new VarTable(); Identifiers = new VarTable(); Letters = new ConstTable(@"Tables/Letters.txt"); Digits = new ConstTable(@"Tables/Digits.txt"); Buffer = ""; StepBack = false; }
/// <summary> /// 获取寄存器,isResult为true,则说明需要返回的是存放结果的寄存器 /// </summary> /// <param name="f">四元式</param> /// <param name="varTable">变量表</param> /// <param name="isResult">指定获取的寄存器是否是用来存放计算结果</param> /// <param name="cmdList">汇编指令列表</param> /// <returns>寄存器名</returns> private string getReg(FourExp f, VarTable varTable, bool isResult, List <AssemblerIns> cmdList) { //返回B或者C所在的寄存器 if (isResult) { if ((f.Arg1 != "") && (varTable.GetAddrInfo(f.Arg1) != "")) { string regB = varTable.GetAddrInfo(f.Arg1); if ((varTable.GetPeekActInfo(f.Arg1) == false) || f.Arg1 == f.Result || regUseTable.GetContent(regB).Count == 1) { return(regB); } } if ((f.Arg2 != "") && (varTable.GetAddrInfo(f.Arg2) != "")) { string regC = varTable.GetAddrInfo(f.Arg1); if ((varTable.GetPeekActInfo(f.Arg2) == false) || f.Arg2 == f.Result || regUseTable.GetContent(regC).Count == 1) { return(regC); } } } //返回未占用寄存器 foreach (string regName in registers) { if (regUseTable.GetContent(regName) == null) { return(regName); } } //随机返回一个已占用的寄存器 Random r = new Random(); while (true) { int i = r.Next(registers.Length); string reg = registers[i]; List <string> varList = new List <string>() { f.Arg1, f.Arg2, f.Result }; if (!regUseTable.Contains(reg, varList)) { //调整变量表和寄存器表中的相关域 doAdjust(reg, varTable, cmdList); return(reg); } } }
/// <summary> /// 跳转之后的调整 /// </summary> /// <param name="f">四元式</param> /// <param name="reg1">寄存器1</param> /// <param name="reg2">寄存器2</param> /// <param name="varTable">变量表</param> /// <param name="cmdList">汇编指令列表</param> private void adjustAfterJump(FourExp f, string reg1, string reg2, VarTable varTable, List <AssemblerIns> cmdList) { if (varTable.GetPeekActInfo(f.Arg1) == false) { cmdList.Add(AssemblerFac.GenSW(reg1, varTable.GetAddr(f.Arg1).ToString(), "$ZERO")); varTable.SetAddrInfo(f.Arg1, ""); regUseTable.GetContent(reg1).Remove(f.Arg1); } if (varTable.GetPeekActInfo(f.Arg2) == false) { cmdList.Add(AssemblerFac.GenSW(reg2, varTable.GetAddr(f.Arg2).ToString(), "$ZERO")); varTable.SetAddrInfo(f.Arg2, ""); regUseTable.GetContent(reg2).Remove(f.Arg2); } }
static void Main(string[] args) { var KeyWords = new ConstTable(@"Tables/KeyWords.txt"); var Delimiters = new ConstTable(@"Tables/Delimiters.txt"); var Operations = new ConstTable(@"Tables/Operations.txt"); var Constants = new VarTable(); var Identifiers = new VarTable(); LexicAnalyzer La = new LexicAnalyzer(KeyWords, Delimiters, Operations, Constants, Identifiers); Token[] res = La.AnalyzeSource("test2"); foreach (string s in La.Output) { Console.WriteLine(s); } Console.WriteLine(Constants); Console.WriteLine(Identifiers); }
//TODO TESTS private static void Initialization(ListController <TokenModel> lc) { var type = lc.GetNext(); var name = TryGetNext(lc, "Variable name expected"); if (!Constants.Alphabet.Contains(name.Text[0])) { throw new ParseException("Unexpected token", name); } if (VarTable.Contains(name.Text) || FuncTable.Contains(name.Text)) { throw new ParseException("Member with the same name is already declared", name); } VarTable.Add(name.Text, type.Text); }
public void Visit(VarList node) { foreach (var n in node) { var variableName = n.AnchorToken.Lexeme; if (VarTable.Contains(variableName)) { throw new SemanticError( "Duplicated variable: " + variableName, n.AnchorToken); } else { VarTable.Add(variableName); } } }
public void Visit(Identifier node) { var variableName = node.AnchorToken.Lexeme; var props = FunTable[currentFunction]; if (props.reference.ContainsKey(variableName)) { } else if (VarTable.Contains(variableName)) { } else { throw new SemanticError( "Undeclared variable: " + variableName, node.AnchorToken); } }
public CodeBuilder( ConstTable KeyWords, ConstTable Operations, VarTable Constants, VarTable Identifiers, ConstTable Goto, VarTable Labels ) { this.KeyWords = KeyWords; this.Operations = Operations; this.Constants = Constants; this.Identifiers = Identifiers; this.Goto = Goto; this.Labels = Labels; output = new StringBuilder(); }
/// <summary> /// Конструктор. /// </summary> public FiniteStateMachine( ConstTable KeyWords, ConstTable Delimiters, ConstTable Operations, VarTable Constants, VarTable Identifiers ) { State = States.Start; this.KeyWords = KeyWords; this.Delimiters = Delimiters; this.Operations = Operations; this.Constants = Constants; this.Identifiers = Identifiers; Letters = new ConstTable(@"Tables/Letters.txt"); Digits = new ConstTable(@"Tables/Digits.txt"); Buffer = ""; StepBack = false; }
/// <summary> /// 初始化变量表 /// </summary> /// <param name="varTable">变量表</param> /// <param name="fourExpList">四元式列表</param> /// <param name="varNameList">变量表中变量名的列表</param> private void initVarTable(VarTable varTable, List <FourExp> fourExpList, List <string> varNameList) { short address = 0x0000; foreach (string varName in varNameList) { //初始化变量表中的变量地址和活跃信息域 varTable.SetAddr(varName, address); address += 4; //varTable.ClearRefeInfo(varName); varTable.ClearActInfo(varName); varTable.PushActInfo(varName, false); //varTable.PushRefeInfo(varName, -1); } //扫描四元式表,在变量表中填入相关信息 int count = fourExpList.Count; int length = count; for (int i = length; i != 0; i--) { string A = fourExpList[i].Result; string B = fourExpList[i].Arg1; string C = fourExpList[i].Arg2; if (A != "") { //varTable.PushRefeInfo(A, -1); varTable.PushActInfo(A, false); } if (B != "") { //varTable.PushRefeInfo(B, count); varTable.PushActInfo(B, true); } if (C != "") { //varTable.PushRefeInfo(C, count); varTable.PushActInfo(C, true); } count--; } }
public override void Translate(VarTable varTable, LabelStack labelStack, List <FourExp> fourExpList) { if (statement1 == null) { string label = labelStack.NewLabel(); string condition = expression.GetValue(varTable, labelStack, fourExpList); fourExpList.Add(FourExpFac.GenJe(condition, 0 + "", label)); statement1.Translate(varTable, labelStack, fourExpList); fourExpList.Add(FourExpFac.GenLabel(label)); } else { string label1 = labelStack.NewLabel(); string label2 = labelStack.NewLabel(); string condition = expression.GetValue(varTable, labelStack, fourExpList); fourExpList.Add(FourExpFac.GenJe(condition, 0 + "", label1)); statement1.Translate(varTable, labelStack, fourExpList); fourExpList.Add(FourExpFac.GenJmp(label2)); fourExpList.Add(FourExpFac.GenLabel(label1)); statement2.Translate(varTable, labelStack, fourExpList); fourExpList.Add(FourExpFac.GenLabel(label2)); } }
//TODO TESTS private static AssingNode VariableAssign(ListController <TokenModel> lc) { var variableToken = lc.GetNext(); CheckEqual(TryGetNext(lc, "= expected"), "=", "= expected"); var func = TryGetNext(lc, "Expression expected"); var res = new AssingNode(); var variable = VarTable.Get(variableToken.Text); res.Left = variable; if (FuncTable.Contains(func.Text)) { lc.SetBack(); var fn = FuncExecute(lc); res.Right = fn; } else { throw new ParseException("Function expected", func); } return(res); }
private static void StampVersion(string path, Version version) { var versionResource = new VersionResource { FileVersion = version.ToString(), ProductVersion = version.ToString() }; var stringFileInfo = new StringFileInfo(); versionResource[stringFileInfo.Key] = stringFileInfo; var stringFileInfoStrings = new StringTable { LanguageID = 1033, CodePage = 1200 }; stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings); stringFileInfoStrings["CompanyName"] = Config.Global.Version.CompanyName; stringFileInfoStrings["FileDescription"] = Config.Global.Version.FileDescription; stringFileInfoStrings["FileVersion"] = version.ToString(); stringFileInfoStrings["InternalName"] = Config.Global.Version.InternalName; stringFileInfoStrings["LegalCopyright"] = Config.Global.Version.LegalCopyright; stringFileInfoStrings["OriginalFilename"] = Config.Global.Version.OriginalFilename; stringFileInfoStrings["ProductName"] = Config.Global.Version.ProductName; stringFileInfoStrings["ProductVersion"] = version.ToString(); var varFileInfo = new VarFileInfo(); versionResource[varFileInfo.Key] = varFileInfo; var varFileInfoTranslation = new VarTable("Translation"); varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation); varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300; versionResource.SaveTo(path); }
/// <summary> /// 生成数据段 /// </summary> /// <param name="varNameList">变量名列表</param> /// <param name="varTable">变量表</param> /// <param name="cmdList">汇编指令列表</param> private void genDataIns(List <string> varNameList, VarTable varTable, List <AssemblerIns> cmdList) { foreach (string varName in varNameList) { if (varTable.GetType(varName) == VariableType.INT || varTable.GetType(varName) == VariableType.CHAR || varTable.GetType(varName) == VariableType.BOOL) { short varValue = (short)varTable.GetValue(varName); short varAddr = varTable.GetAddr(varName); cmdList.Add(AssemblerFac.GenLUI("$T0", varValue.ToString())); cmdList.Add(AssemblerFac.GenSRL("$T0", "$T0", Convert.ToString(16))); cmdList.Add(AssemblerFac.GenSW("$T0", varAddr.ToString(), "$ZERO")); } else { int value = varTable.GetValue(varName); short high = (short)(value >> 16); short varAddr = varTable.GetAddr(varName); cmdList.Add(AssemblerFac.GenLUI("$T0", high.ToString())); short low = (short)(value & 0xffff); cmdList.Add(AssemblerFac.GenORI("$T0", "$T0", low.ToString())); cmdList.Add(AssemblerFac.GenSW("$T0", varAddr.ToString(), "$ZERO")); } } }
public void Save(bool autoHandleDependencies = false) { lock (this) { if (_manifest != null) { _pendingChanges = _manifest.Modified || _pendingChanges; } // Logger.Message("Saving Binary '{0}' : Pending Changes: {1} ", _filename, _pendingChanges); if (_pendingChanges) { // saves any changes made to the binary. // work on a back up of the file var tmpFilename = _filename.CreateWritableWorkingCopy(); try { // remove any digital signatures from the binary before doing anything if (!IsManaged) { StripSignatures(tmpFilename); // this is irrelevant if the binary is managed--we'll be writing out a new one. } // rewrite any native resources that we want to change. if (IsManaged && ILOnly) { // we can only edit the file if it's IL only, mixed mode assemblies can only be strong named, signed and native-resource-edited. // set the strong name key data MutableAssembly.PublicKey = StrongNameKey.ToList(); // change any assembly attributes we need to change if (MutableAssembly != null) { if (StrongNameKeyCertificate != null) { foreach (var ar in MutableAssembly.AssemblyReferences) { if (!ar.PublicKeyToken.Any()) { var dep = FindAssembly(ar.Name.Value, ar.Version.ToString()); if (dep == null) { // can't strong name a file that doesn't have its deps all strong named. throw new ClrPlusException("dependent assembly '{0}-{1}' not available for strong naming".format(ar.Name.Value, ar.Version.ToString())); } lock (dep) { // this should wait until the dependency is finished saving, right? } if (dep.MutableAssembly.PublicKey.IsNullOrEmpty()) { if (autoHandleDependencies) { Console.WriteLine( "Warning: Non-strong-named dependent reference found: '{0}-{1}' updating with same strong-name-key.", ar.Name, ar.Version); dep.StrongNameKeyCertificate = StrongNameKeyCertificate; dep.SigningCertificate = SigningCertificate; dep.AssemblyCopyright = AssemblyCopyright; dep.AssemblyCompany = AssemblyCompany; dep.AssemblyProduct = AssemblyProduct; dep.Save(); } else { throw new ClrPlusException("dependent assembly '{0}-{1}' not strong named".format(ar.Name.Value, ar.Version.ToString())); } } (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKeyToken = dep.MutableAssembly.PublicKeyToken.ToList(); (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKey = dep.MutableAssembly.PublicKey; } } } // we should see if we can get assembly attributes, since sometimes they can be set, but not the native ones. try { foreach (var a in MutableAssembly.AssemblyAttributes) { var attributeArgument = (a.Arguments.FirstOrDefault() as MetadataConstant); if (attributeArgument != null) { var attributeName = a.Type.ToString(); switch (attributeName) { case "System.Reflection.AssemblyTitleAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyTitle) ? string.Empty : AssemblyTitle; break; case "System.Reflection.AssemblyDescriptionAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyDescription) ? string.Empty : AssemblyDescription; break; case "System.Reflection.AssemblyCompanyAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyCompany) ? string.Empty : AssemblyCompany; break; case "System.Reflection.AssemblyProductAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyProduct) ? string.Empty : AssemblyProduct; break; case "System.Reflection.AssemblyVersionAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyVersion) ? string.Empty : AssemblyVersion; break; case "System.Reflection.AssemblyFileVersionAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyFileVersion) ? string.Empty : AssemblyFileVersion; break; case "System.Reflection.AssemblyCopyrightAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyCopyright) ? string.Empty : AssemblyCopyright; break; case "System.Reflection.AssemblyTrademarkAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyTrademark) ? string.Empty : AssemblyTrademark; break; case "BugTrackerAttribute": attributeArgument.Value = string.IsNullOrEmpty(BugTracker) ? string.Empty : BugTracker; break; } } } } catch { // hmm. carry on. } } // save it to disk using (var peStream = File.Create(tmpFilename)) { PeWriter.WritePeToStream(MutableAssembly, _host, peStream); } } // update native metadata try { var ri = new ResourceInfo(); ri.Load(tmpFilename); if (_manifest != null && _manifest.Modified) { // GS01: We only support one manifest right now. // so we're gonna remove the extra ones. // figure out the bigger case later. var manifestKeys = ri.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_MANIFEST).ToArray(); foreach (var k in manifestKeys) { ri.Resources.Remove(k); } var manifestResource = new ManifestResource(); manifestResource.ManifestText = _manifest.ToString(); ri.Resources.Add(new ResourceId(ResourceTypes.RT_MANIFEST), new List<Resource> { manifestResource }); manifestResource.SaveTo(tmpFilename); } VersionResource versionResource; StringTable versionStringTable; var versionKey = ri.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_VERSION).FirstOrDefault(); if (versionKey != null) { versionResource = ri.Resources[versionKey].First() as VersionResource; versionStringTable = (versionResource["StringFileInfo"] as StringFileInfo).Strings.Values.First(); } else { versionResource = new VersionResource(); ri.Resources.Add(new ResourceId(ResourceTypes.RT_VERSION), new List<Resource> { versionResource }); var sfi = new StringFileInfo(); versionResource["StringFileInfo"] = sfi; sfi.Strings["040904b0"] = (versionStringTable = new StringTable("040904b0")); var vfi = new VarFileInfo(); versionResource["VarFileInfo"] = vfi; var translation = new VarTable("Translation"); vfi.Vars["Translation"] = translation; translation[0x0409] = 0x04b0; } versionResource.FileVersion = FileVersion; versionResource.ProductVersion = ProductVersion; versionStringTable["ProductName"] = ProductName; versionStringTable["CompanyName"] = CompanyName; versionStringTable["FileDescription"] = FileDescription; versionStringTable["Comments"] = _comments; versionStringTable["Assembly Version"] = _assemblyVersion; versionStringTable["FileVersion"] = _fileVersion; versionStringTable["ProductVersion"] = _productVersion; versionStringTable["InternalName"] = _internalName; versionStringTable["OriginalFilename"] = _originalFilename; versionStringTable["LegalCopyright"] = _legalCopyright; versionStringTable["LegalTrademarks"] = _legalTrademarks; versionStringTable["BugTracker"] = _bugTracker; versionResource.SaveTo(tmpFilename); } catch (Exception e) { Console.WriteLine("{0} -- {1}", e.Message, e.StackTrace); } // strong name the binary if (IsManaged && StrongNameKeyCertificate != null && (StrongNameKeyCertificate.Certificate.PrivateKey is RSACryptoServiceProvider)) { ApplyStrongName(tmpFilename, StrongNameKeyCertificate); } // sign the binary if (_signingCertificate != null) { SignFile(tmpFilename, SigningCertificate.Certificate); } _filename.TryHardToDelete(); File.Move(tmpFilename, _filename); } catch (Exception e) { #if TODO Logger.Error(e); #endif // get rid of whatever we tried tmpFilename.TryHardToDelete(); // as you were... throw; } } _pendingChanges = false; if (_manifest != null) { _manifest.Modified = false; } } }
public Task<Binary> Save() { lock (this) { if (_saving != null) { return _saving; } if (Unloaded) { throw new CoAppBinaryException("Binary '{0}' has been unloaded", Filename); } if (!Modified) { return this.AsResultTask(); } _saving = Task<Binary>.Factory.StartNew(() => { // Console.WriteLine("Actual Signing Process started for [{0}]/[{1}]", Filename , WorkingCopy); if (!IsManaged) { StripSignatures(WorkingCopy); // this is irrelevant if the binary is managed--we'll be writing out a new one. } if (!_loadOptions.HasFlag(BinaryLoadOptions.NoManaged) && IsManaged && (_modifiedManaged || _modifiedResources)) { WaitForResourceAndManagedLoaders(); // handle managed code rewrites // we can only edit the file if it's IL only, mixed mode assemblies can only be strong named, signed and native-resource-edited. // set the strong name key data if (!StrongNameKey.IsNullOrEmpty()) { if (_mutableAssembly == null) { Console.WriteLine("HEY! : {0}", Filename); } _mutableAssembly.PublicKey = StrongNameKey.ToList(); // change any assembly attributes we need to change if (_mutableAssembly != null) { if (StrongNameKeyCertificate != null) { foreach (var ar in _mutableAssembly.AssemblyReferences) { // rewrite assembly references that need to be updated. if (!ar.PublicKeyToken.Any()) { var dep = FindAssembly(ar.Name.Value, ar.Version.ToString()); if (dep == null) { // can't strong name a file that doesn't have its deps all strong named. throw new CoAppException("dependent assembly '{0}-{1}' not available for strong naming".format(ar.Name.Value, ar.Version.ToString())); } if (dep._mutableAssembly.PublicKey.IsNullOrEmpty()) { if (!_loadOptions.HasFlag(BinaryLoadOptions.NoUnsignedManagedDependencies)) { Console.WriteLine( "Warning: Non-strong-named dependent reference found: '{0}-{1}' updating with same strong-name-key.", ar.Name, ar.Version); dep.StrongNameKeyCertificate = StrongNameKeyCertificate; dep.SigningCertificate = SigningCertificate; dep.AssemblyCopyright = AssemblyCopyright; dep.AssemblyCompany = AssemblyCompany; dep.AssemblyProduct = AssemblyProduct; // wait for the dependency to finish saving. dep.Save().Wait(); } else { throw new CoAppException("dependent assembly '{0}-{1}' not strong named".format(ar.Name.Value, ar.Version.ToString())); } } (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKeyToken = dep._mutableAssembly.PublicKeyToken.ToList(); (ar as Microsoft.Cci.MutableCodeModel.AssemblyReference).PublicKey = dep._mutableAssembly.PublicKey; } } } } // we should see if we can get assembly attributes, since sometimes they can be set, but not the native ones. try { if (!_mutableAssembly.AssemblyAttributes.IsNullOrEmpty()) { foreach (var a in _mutableAssembly.AssemblyAttributes) { var attributeArgument = (a.Arguments.FirstOrDefault() as MetadataConstant); if (attributeArgument != null) { var attributeName = a.Type.ToString(); switch (attributeName) { case "System.Reflection.AssemblyTitleAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyTitle) ? string.Empty : AssemblyTitle; break; case "System.Reflection.AssemblyDescriptionAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyDescription) ? string.Empty : AssemblyDescription; break; case "System.Reflection.AssemblyCompanyAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyCompany) ? string.Empty : AssemblyCompany; break; case "System.Reflection.AssemblyProductAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyProduct) ? string.Empty : AssemblyProduct; break; //case "System.Reflection.AssemblyVersionAttribute": // attributeArgument.Value = (string)AssemblyVersion; // break; case "System.Reflection.AssemblyFileVersionAttribute": attributeArgument.Value = (string)AssemblyFileVersion; break; case "System.Reflection.AssemblyCopyrightAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyCopyright) ? string.Empty : AssemblyCopyright; break; case "System.Reflection.AssemblyTrademarkAttribute": attributeArgument.Value = string.IsNullOrEmpty(AssemblyTrademark) ? string.Empty : AssemblyTrademark; break; case "BugTrackerAttribute": attributeArgument.Value = string.IsNullOrEmpty(BugTracker) ? string.Empty : BugTracker; break; } } } } } catch { // hmm. carry on. } } // save it to disk WorkingCopy.TryHardToMakeFileWriteable(); using (var peStream = File.Create(WorkingCopy)) { PeWriter.WritePeToStream(_mutableAssembly, _host, peStream); } } if (!_loadOptions.HasFlag(BinaryLoadOptions.NoManifest) && Manifest.Value != null && Manifest.Value.Modified) { // rewrite Manifests // GS01: We only support one manifest right now. // so we're gonna remove the extra ones. // figure out the bigger case later. var manifestKeys = NativeResources.Value.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_MANIFEST).ToArray(); foreach (var k in manifestKeys) { var v = NativeResources.Value.Resources[k]; if (!v.IsNullOrEmpty()) { foreach (var inst in v) { Resource.Delete(WorkingCopy, inst.Type, inst.Name, inst.Language); } } NativeResources.Value.Resources.Remove(k); } var IsLibrary = Path.GetExtension(Filename).ToLower() == ".dll"; var manifestResource = new ManifestResource(IsLibrary ? ManifestType.IsolationAware : ManifestType.CreateProcess) {ManifestText = Manifest.Value.ToString(), Language = 1033}; // GS01: I'm hardcoding this for now. We're probably gonna have to be way smarter about this. NativeResources.Value.Resources.Add(new ResourceId(ResourceTypes.RT_MANIFEST), new List<Resource> { manifestResource }); manifestResource.SaveTo(WorkingCopy); } if (!_loadOptions.HasFlag(BinaryLoadOptions.NoResources) && _modifiedResources) { // rewrite Resources VersionResource versionResource; StringTable versionStringTable; var versionKey = NativeResources.Value.Resources.Keys.FirstOrDefault(each => each.ResourceType == ResourceTypes.RT_VERSION); if (versionKey != null) { versionResource = NativeResources.Value.Resources[versionKey].First() as VersionResource; versionStringTable = (versionResource["StringFileInfo"] as StringFileInfo).Strings.Values.First(); } else { versionResource = new VersionResource(); NativeResources.Value.Resources.Add(new ResourceId(ResourceTypes.RT_VERSION), new List<Resource> { versionResource }); var sfi = new StringFileInfo(); versionResource["StringFileInfo"] = sfi; sfi.Strings["040904b0"] = (versionStringTable = new StringTable("040904b0")); var vfi = new VarFileInfo(); versionResource["VarFileInfo"] = vfi; var translation = new VarTable("Translation"); vfi.Vars["Translation"] = translation; translation[0x0409] = 0x04b0; } versionResource.FileVersion = FileVersion; versionResource.ProductVersion = ProductVersion; versionStringTable["ProductName"] = ProductName; versionStringTable["CompanyName"] = CompanyName; versionStringTable["FileDescription"] = FileDescription; versionStringTable["Comments"] = _comments; versionStringTable["Assembly Version"] = AssemblyVersion.Value; versionStringTable["FileVersion"] = _fileVersion; versionStringTable["ProductVersion"] = _productVersion; versionStringTable["InternalName"] = _internalName; versionStringTable["OriginalFilename"] = _originalFilename; versionStringTable["LegalCopyright"] = _legalCopyright; versionStringTable["LegalTrademarks"] = _legalTrademarks; versionStringTable["BugTracker"] = _bugTracker; versionResource.SaveTo(WorkingCopy); } if (!_loadOptions.HasFlag(BinaryLoadOptions.NoSignature) && _modifiedSignature && _signingCertificate != null) { // Strongname & Sign the package // strong name the binary (if we're doing managed stuff). if (!_loadOptions.HasFlag(BinaryLoadOptions.NoManaged) && IsManaged && StrongNameKeyCertificate != null && (StrongNameKeyCertificate.Certificate.PrivateKey is RSACryptoServiceProvider)) { ApplyStrongName(WorkingCopy, StrongNameKeyCertificate); } // sign the binary SignFile(WorkingCopy, SigningCertificate.Certificate); } if (_loadingMD5 != null) { _loadingMD5 = null; } LoadMD5().Wait(); // Console.WriteLine("Replacing original File [{0}]", Filename); Filename.TryHardToDelete(); File.Copy(WorkingCopy, Filename); _modified = false; _modifiedResources = false; _modifiedManaged = false; _modifiedSignature = false; // Console.WriteLine("Completed Signing Process started for [{0}]/[{1}]", Filename, WorkingCopy); return this; }); _saving.ContinueWith((a) => { _saving = null; }, TaskContinuationOptions.AttachedToParent); } return _saving; }