private CompilerResults CompileAssemblyFromSourceImpl( IEnumerable<string> sourceContents, string outputAssemblyName, CodeDomProvider provider) { var parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = string.IsNullOrEmpty(outputAssemblyName); parameters.IncludeDebugInformation = false; parameters.TreatWarningsAsErrors = true; parameters.CompilerOptions = "/optimize"; parameters.OutputAssembly = outputAssemblyName; if (this.ReferenceAssemblies.Count() > 0) { parameters.ReferencedAssemblies.AddRange(this.ReferenceAssemblies.ToArray()); } return provider.CompileAssemblyFromSource(parameters, sourceContents.ToArray()); }
private CompilerResults CompileWithCodeDom(List <string> filenames, List <string> sources, ICollection <Assembly> referencedAssemblies) { #if CODEDOM CodeDomProvider provider = CodeDomProvider.CreateProvider(language); // A special provider is required to compile code using C# 6. // However, it requires a reference to the following NuGet package: // https://www.nuget.org/packages/Microsoft.CodeDom.Providers.DotNetCompilerPlatform/ //CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.IncludeDebugInformation = includeDebugInformation; if (optimizeCode) { cp.CompilerOptions = "/optimize "; } // If running on the Mono VM, disable all warnings in the generated // code because these are treated as errors by the Mono compiler. if (runningOnMono) { cp.CompilerOptions += "/warn:0 "; } List <string> assemblyNames = new List <string>(); foreach (Assembly assembly in referencedAssemblies) { try { assemblyNames.Add(assembly.Location); } catch (NotSupportedException) { // do nothing - this assembly does not have a location e.g. it is in memory } catch (Exception e) { Console.WriteLine("Warning, could not add location for assembly: " + assembly); Console.WriteLine(e); } } // we must only add references to assemblies that are actually referenced by the code -- not all the assemblies in memory during model compilation (that could be a much larger set) foreach (string s in assemblyNames) { cp.ReferencedAssemblies.Add(s); } System.CodeDom.Compiler.CompilerResults cr; cp.GenerateInMemory = generateInMemory; if (!cp.GenerateInMemory) { cp.OutputAssembly = Path.ChangeExtension(filenames[0], ".dll"); try { if (File.Exists(cp.OutputAssembly)) { File.Delete(cp.OutputAssembly); } } catch { for (int i = 0; ; i++) { cp.OutputAssembly = Path.ChangeExtension(Path.ChangeExtension(filenames[0], null) + DateTime.Now.Millisecond, ".dll"); try { if (File.Exists(cp.OutputAssembly)) { File.Delete(cp.OutputAssembly); } break; } catch { } } } } // TODO: allow compiled assemblies to be unloaded, by compiling them as Add-ins (see AddInAttribute) if (!writeSourceFiles) { cr = provider.CompileAssemblyFromSource(cp, sources.ToArray()); } else { cr = provider.CompileAssemblyFromFile(cp, filenames.ToArray()); } List <string> errors = new List <string>(cr.Errors.Count); foreach (var error in cr.Errors) { errors.Add(error.ToString()); } Assembly compiledAssembly; try { compiledAssembly = cr.CompiledAssembly; } catch { compiledAssembly = null; } return(new CompilerResults(compiledAssembly, errors.Count == 0, errors)); #else throw new NotSupportedException("This assembly was compiled without CodeDom support. To use CodeDom, recompile with the CODEDOM compiler flag."); #endif }
public string Compile(ScriptMetaData data, ref string _script) { // Add "using", "inherit", default constructor, etc around script. string script = PreProcessScript(ref _script); // Get filename based on content string md5Sum = System.Convert.ToBase64String( MD5Sum.ComputeHash( System.Text.Encoding.ASCII.GetBytes(script) )); // Unique name for this assembly ScriptAssemblyName = "SECS_Script_" + FileNameFixer.Replace(md5Sum, "_"); string OutFile = Path.Combine(ScriptEnginesPath, ScriptAssemblyName + ".dll"); // Make sure target dir exist if (!Directory.Exists(ScriptEnginesPath)) { try { Directory.CreateDirectory(ScriptEnginesPath); } catch { } } // Already exist? No point in recompiling if (File.Exists(OutFile)) { return(OutFile); } // // Dump source code // string dumpFile = OutFile + ".txt"; try { if (File.Exists(dumpFile)) { File.Delete(dumpFile); } File.WriteAllText(dumpFile, script); } catch (Exception e) { m_log.DebugFormat("[{0}] Exception trying to dump script source code to file \"{1}\": {2}", Name, dumpFile, e.ToString()); } // // COMPILE // CompilerParameters parameters = new CompilerParameters(); parameters.IncludeDebugInformation = true; //string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory); foreach (string file in AppDomainAssemblies) { parameters.ReferencedAssemblies.Add(file); m_log.DebugFormat("[{0}] Adding reference for compile: \"{1}\".", Name, file); } //lock (commandProvider) //{ // foreach (string key in commandProvider.Keys) // { // IScriptCommandProvider cp = commandProvider[key]; // string // file = cp.GetType().Assembly.Location; // parameters.ReferencedAssemblies.Add(file); // m_log.DebugFormat("[{0}] Loading command provider assembly \"{1}\" into AppDomain: \"{2}\".", Name, // key, file); // } //} parameters.GenerateExecutable = false; parameters.OutputAssembly = OutFile; parameters.IncludeDebugInformation = true; //parameters.WarningLevel = 1; // Should be 4? parameters.TreatWarningsAsErrors = false; // Do compile CompilerResults results = CompileProvider.CompileAssemblyFromSource(parameters, script); // // WARNINGS AND ERRORS // //TODO int display = 5; if (results.Errors.Count > 0) { string errtext = String.Empty; foreach (CompilerError CompErr in results.Errors) { // Show 5 errors max // if (display <= 0) { break; } display--; string severity = "Error"; if (CompErr.IsWarning) { severity = "Warning"; } //TODO: Implement KeyValuePair <int, int> lslPos = new KeyValuePair <int, int>(); //lslPos = "NOT IMPLEMENTED";// FindErrorPosition(CompErr.Line, CompErr.Column); string text = CompErr.ErrorText; // The Second Life viewer's script editor begins // countingn lines and columns at 0, so we subtract 1. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n", lslPos.Key - 1, lslPos.Value - 1, CompErr.ErrorNumber, text, severity); } if (!File.Exists(OutFile)) { throw new Exception(errtext); } } // TODO: Process errors return(OutFile); }
static public Assembly BuildDll(string code, string sourcePath) { //IDictionary<string, string> compParams = // new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } }; //CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp", compParams); CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp"); string outputDll = sourcePath + "ApirController.dll"; string path = DllBuilder.AssemblyDirectory; System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.OutputAssembly = outputDll; parameters.ReferencedAssemblies.Add(@"System.dll"); parameters.ReferencedAssemblies.Add(@"System.Core.dll"); parameters.ReferencedAssemblies.Add(@"System.Net.Http.dll"); parameters.ReferencedAssemblies.Add(@"System.Net.Http.WebRequest.dll"); parameters.ReferencedAssemblies.Add(path + @"\System.Net.Http.Formatting.dll"); parameters.ReferencedAssemblies.Add(path + @"\System.Web.Http.dll"); //parameters.ReferencedAssemblies.Add(@"System.Net.Http.Formatting.dll"); //parameters.ReferencedAssemblies.Add(@"System.Web.Http.dll"); parameters.ReferencedAssemblies.Add(@"System.Data.dll"); parameters.ReferencedAssemblies.Add(@"System.Data.DataSetExtensions.dll"); parameters.ReferencedAssemblies.Add(@"System.xml.dll"); parameters.ReferencedAssemblies.Add(@"System.xml.Linq.dll"); parameters.ReferencedAssemblies.Add(@"System.Configuration.dll"); parameters.ReferencedAssemblies.Add(path + @"\NLog.dll"); parameters.CompilerOptions = "/doc:" + sourcePath + "xmlComments.xml"; #if DEBUG parameters.IncludeDebugInformation = true; parameters.GenerateInMemory = false; var fileName = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\swaDebug.cs")); File.WriteAllText(fileName, code); CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, fileName); #else CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code); #endif using (StreamWriter outfile = new StreamWriter(sourcePath + "swaError.txt")) { if (results.Errors.Count > 0) { if (sourcePath != null) { foreach (CompilerError CompErr in results.Errors) { outfile.WriteLine( "Line number " + CompErr.Line + ", Error Number: " + CompErr.ErrorNumber + ", '" + CompErr.ErrorText + ";" + Environment.NewLine + Environment.NewLine); } } throw new Exception("Compile Error"); } else { outfile.WriteLine("Build Succeeded"); return(Assembly.LoadFrom(outputDll)); } } }
private Assembly CompileCode(string code) { string options = "/target:library /optimize "; options += "/lib:\"" + Path.Combine(SkylinePath.Application, "Cities_Data\\Managed") + "\" "; CompilerParameters parameters = new CompilerParameters(); parameters.ReferencedAssemblies.Add("mscorlib.dll"); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); parameters.ReferencedAssemblies.Add("ICities.dll"); parameters.ReferencedAssemblies.Add("UnityEngine.dll"); parameters.ReferencedAssemblies.Add("Assembly-CSharp.dll"); parameters.ReferencedAssemblies.Add("Assembly-CSharp-firstpass.dll"); foreach (string directory in Directory.GetDirectories(SkylinePath.Mods, "*", SearchOption.TopDirectoryOnly)) { options += "/lib:\"" + directory + "\" "; foreach (string file in Directory.GetFiles(directory, "*.dll", SearchOption.TopDirectoryOnly)) { parameters.ReferencedAssemblies.Add(Path.GetFileName(file)); } } parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.IncludeDebugInformation = false; parameters.CompilerOptions = options; Assembly colossalManaged = typeof(ColossalFramework.Plugins.PluginManager).Assembly; if (colossalManaged == null) { Log.Error("Unable to resolve ColossalManaged.dll"); return(null); } Type codeProviderType = colossalManaged.GetType("ColossalFramework.Plugins.ColossalCSharpCodeProvider"); if (codeProviderType == null) { Log.Error("Unable to resolve ColossalCSharpCodeProvider type."); } ConstructorInfo ctor = codeProviderType.GetConstructor(new Type[0]); //CodeDomProvider codeProvider = new CSharpCodeProvider(); CodeDomProvider codeProvider = (CodeDomProvider)ctor.Invoke(new object[0]); CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(parameters, code); if (compilerResults.NativeCompilerReturnValue != 0) { //Log.Error("Failed to compile code: {0}", code); // TODO Logging methods for blank strings and values (int, double, ... ) see Console.WriteLine(..); DumpCompilerErrors(compilerResults); return(null); } else { return(compilerResults.CompiledAssembly); } }
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second switch */ private void GoodB2G2() { string data; switch (6) { case 6: data = ""; /* Initialize data */ { /* read user input from console with ReadLine */ try { /* POTENTIAL FLAW: Read data from the console using ReadLine */ data = Console.ReadLine(); } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; break; } switch (7) { case 7: int?parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } break; default: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); break; } }
public static Assembly BuildAssembly(Properties props, AssemblyName assemblyName, ref string nameSpace) { WebClient client = new WebClient(); if (props.WSDLUri != null) { CredentialCache cc = new CredentialCache(); cc.Add(new Uri(props.WSDLUri), props.AuthMode, props.GetCredentials()); client.Credentials = cc; } ServiceDescription description; using (Stream stream = client.OpenRead(props.WSDLUri)) { description = ServiceDescription.Read(stream); } ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //importer.ProtocolName = "Soap12"; importer.AddServiceDescription(description, null, null); importer.Style = ServiceDescriptionImportStyle.Client; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; CleanupSchema(props, client, description, importer); CodeNamespace cns = new CodeNamespace(nameSpace); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cns); ServiceDescriptionImportWarnings warning = importer.Import(cns, ccu); if (warning != ServiceDescriptionImportWarnings.NoCodeGenerated) { if (props.LogStreams) { foreach (CodeMemberMethod cmm in ccu.Namespaces[0].Types.Cast <CodeTypeDeclaration>().SelectMany(t => t.Members.OfType <CodeMemberMethod>() .Where(m => m.CustomAttributes.Cast <CodeAttributeDeclaration>() .Any(c => c.Name.EndsWith("SoapDocumentMethodAttribute"))))) { cmm.CustomAttributes.Add(new CodeAttributeDeclaration("SoapLoggerExtensionAttribute")); } } if (props.FixNETBug) { foreach (CodeTypeDeclaration cd in ccu.Namespaces[0].Types.Cast <CodeTypeDeclaration>() .Where(c => c.CustomAttributes.Cast <CodeAttributeDeclaration>().All(cad => cad.AttributeType.BaseType != "System.Xml.Serialization.XmlTypeAttribute") && c.CustomAttributes.Cast <CodeAttributeDeclaration>().Any(cad => cad.AttributeType.BaseType != "System.SerializableAttribute"))) { cd.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(System.Xml.Serialization.XmlTypeAttribute)))); } foreach (CodeAttributeDeclaration cd in ccu.Namespaces[0].Types.Cast <CodeTypeDeclaration>() .SelectMany(c => c.CustomAttributes.Cast <CodeAttributeDeclaration>()) .Where(cad => cad.AttributeType.BaseType == "System.Xml.Serialization.XmlTypeAttribute" && String.IsNullOrEmpty((string)cad.Arguments.Cast <CodeAttributeArgument>().Where(arg => arg.Name == "Namespace").Select(arg => ((CodePrimitiveExpression)arg.Value).Value).FirstOrDefault()) && (cad.Arguments.Cast <CodeAttributeArgument>().All(arg => arg.Name != "IncludeInSchema") || cad.Arguments.Cast <CodeAttributeArgument>().Single(arg => arg.Name == "IncludeInSchema").Value == new CodePrimitiveExpression(true)))) { var a = cd.Arguments.Cast <CodeAttributeArgument>().Where(e => e.Name == "Namespace").FirstOrDefault(); if (a == null) { cd.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(description.TargetNamespace))); } else { a.Value = new CodePrimitiveExpression(description.TargetNamespace); } } } if (props.LogStreams) { CodeMemberProperty cmmRawXmlResponse = new CodeMemberProperty(); cmmRawXmlResponse.Name = "RawXmlResponse"; cmmRawXmlResponse.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmmRawXmlResponse.Type = new CodeTypeReference(typeof(string)); cmmRawXmlResponse.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("SoapLoggerExtension"), "XmlResponse"))); ccu.Namespaces[0].Types[0].Members.Add(cmmRawXmlResponse); CodeMemberProperty cmmRawXmlRequest = new CodeMemberProperty(); cmmRawXmlRequest.Name = "RawXmlRequest"; cmmRawXmlRequest.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmmRawXmlRequest.Type = new CodeTypeReference(typeof(string)); cmmRawXmlRequest.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("SoapLoggerExtension"), "XmlRequest"))); ccu.Namespaces[0].Types[0].Members.Add(cmmRawXmlRequest); } CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); string[] assemblyRefs = new string[] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll", Assembly.GetExecutingAssembly().Location }; CompilerParameters parms = new CompilerParameters(assemblyRefs); parms.GenerateInMemory = false; parms.CompilerOptions = "/optimize"; parms.OutputAssembly = assemblyName.CodeBase; parms.IncludeDebugInformation = true; StringBuilder sb = new StringBuilder(); provider.GenerateCodeFromCompileUnit(ccu, new StringWriter(sb), null); // Awfull hack to fix a weird bug with .Net proxy generation (???) sb = sb.Replace("[][]", "[]"); CompilerResults cr = provider.CompileAssemblyFromSource(parms, sb.ToString()); //cr = provider.CompileAssemblyFromDom(parms, ccu); if (props.KeepSource) { //sb.ToString().Dump(); } if (cr.Errors.Count > 0) { throw new Exception("The assembly generation failed: " + String.Join("\r\n", cr.Errors.Cast <CompilerError>().Select(c => c.ErrorText).ToArray())); } else { return(cr.CompiledAssembly); } } return(null); }
/// <summary>Compiles the source code passed and returns the Type with the name className.</summary> /// <param name="classStr">The Source Code of the class in the specified language</param> /// <param name="className">The Name of the Type that must be returned</param> /// <returns>The Type generated by runtime compilation of the class source.</returns> /// <param name="lang">One of the .NET Languages</param> public static Type ClassFromString(string classStr, string className, NetLanguage lang) { if (classStr.Length < 4) { throw new BadUsageException( "There is not enough text to be a proper class, load your class and try again"); } var cp = new CompilerParameters(); //cp.ReferencedAssemblies.Add("System.dll"); //cp.ReferencedAssemblies.Add("System.Data.dll"); //cp.ReferencedAssemblies.Add(typeof(ClassBuilder).Assembly.GetModules()[0].FullyQualifiedName); bool mustAddSystemData = false; lock (mReferencesLock) { if (mReferences == null) { var arr = new ArrayList(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { Module module = assembly.GetModules()[0]; if (module.Name == "mscorlib.dll" || module.Name == "<Unknown>") { continue; } if (module.Name == "System.Data.dll") { mustAddSystemData = true; } if (File.Exists(module.FullyQualifiedName)) { arr.Add(module.FullyQualifiedName); } } mReferences = (string[])arr.ToArray(typeof(string)); } } cp.ReferencedAssemblies.AddRange(mReferences); cp.GenerateExecutable = false; cp.GenerateInMemory = true; cp.IncludeDebugInformation = false; var code = new StringBuilder(); switch (lang) { case NetLanguage.CSharp: code.Append("using System; using FileHelpers;"); if (mustAddSystemData) { code.Append(" using System.Data;"); } break; case NetLanguage.VbNet: if ( CultureInfo.CurrentCulture.CompareInfo.IndexOf(classStr, "Imports System", CompareOptions.IgnoreCase) == -1) { code.Append("Imports System\n"); } if ( CultureInfo.CurrentCulture.CompareInfo.IndexOf(classStr, "Imports FileHelpers", CompareOptions.IgnoreCase) == -1) { code.Append("Imports FileHelpers\n"); } if (mustAddSystemData && CultureInfo.CurrentCulture.CompareInfo.IndexOf(classStr, "Imports System.Data", CompareOptions.IgnoreCase) == -1) { code.Append("Imports System.Data\n"); } break; } code.Append(classStr); CodeDomProvider prov = null; switch (lang) { case NetLanguage.CSharp: prov = CodeDomProvider.CreateProvider("cs"); break; case NetLanguage.VbNet: prov = CodeDomProvider.CreateProvider("vb"); break; } var cr = prov.CompileAssemblyFromSource(cp, code.ToString()); if (cr.Errors.HasErrors) { var error = new StringBuilder(); error.Append("Error Compiling Expression: " + StringHelper.NewLine); foreach (CompilerError err in cr.Errors) { error.AppendFormat("Line {0}: {1}\n", err.Line, err.ErrorText); } throw new RunTimeCompilationException(error.ToString(), classStr, cr.Errors); } // Assembly.Load(cr.CompiledAssembly.); if (className != string.Empty) { return(cr.CompiledAssembly.GetType(className, true, true)); } else { Type[] ts = cr.CompiledAssembly.GetTypes(); if (ts.Length > 0) { foreach (var t in ts) { if (t.FullName.StartsWith("My.My") == false && t.IsDefined(typeof(TypedRecordAttribute), false)) { return(t); } } } throw new BadUsageException("The compiled assembly does not have any type inside."); } }
protected internal bool CompileAndRun(string[] linesOfCode, object evaluationParameter, object additionalParameter) { CompilerParameters CompilerParams = new CompilerParameters(); CompilerParams.GenerateInMemory = true; CompilerParams.TreatWarningsAsErrors = false; CompilerParams.GenerateExecutable = false; string[] referencesSystem = new string[] { "System.dll", "System.Windows.Forms.dll", "System.Data.dll", "System.Xml.dll", "System.Core.dll", "System.Drawing.dll" }; string[] referencesDX = new string[] { AssemblyInfo.SRAssemblyData, AssemblyInfo.SRAssemblyOfficeCore, AssemblyInfo.SRAssemblyPrintingCore, AssemblyInfo.SRAssemblyPrinting, AssemblyInfo.SRAssemblyDocs, AssemblyInfo.SRAssemblyUtils }; string[] referencesDXModule = GetModuleAssemblies(); string[] references = new string[referencesSystem.Length + referencesDX.Length + referencesDXModule.Length]; for (int referenceIndex = 0; referenceIndex < referencesSystem.Length; referenceIndex++) { references[referenceIndex] = referencesSystem[referenceIndex]; } for (int i = 0, initial = referencesSystem.Length; i < referencesDX.Length; i++) { Assembly assembly = Assembly.Load(referencesDX[i] + AssemblyInfo.FullAssemblyVersionExtension); if (assembly != null) { references[i + initial] = assembly.Location; } } for (int i = 0, initial = referencesSystem.Length + referencesDX.Length; i < referencesDXModule.Length; i++) { Assembly assembly = Assembly.Load(referencesDXModule[i] + AssemblyInfo.FullAssemblyVersionExtension); if (assembly != null) { references[i + initial] = assembly.Location; } } CompilerParams.ReferencedAssemblies.AddRange(references); CodeDomProvider provider = GetCodeDomProvider(); CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, linesOfCode); if (compile.Errors.HasErrors) { //string text = "Compile error: "; //foreach(CompilerError ce in compile.Errors) { // text += "rn" + ce.ToString(); //} //MessageBox.Show(text); return(false); } Module module = null; try { module = compile.CompiledAssembly.GetModules()[0]; } catch { } Type moduleType = null; if (module == null) { return(false); } moduleType = module.GetType(GetExampleClassName()); MethodInfo methInfo = null; if (moduleType == null) { return(false); } methInfo = moduleType.GetMethod("Process"); if (methInfo != null) { try { methInfo.Invoke(null, new object[] { evaluationParameter, additionalParameter }); } catch (Exception) { return(false);// an error } return(true); } return(false); }
/// <summary> /// Компилировать исходный код формул калькулятора /// </summary> public bool CompileSource() { try { // загрузка исходного кода класса CalcEngine string source; using (Stream stream = Assembly.GetExecutingAssembly(). GetManifestResourceStream("Scada.Server.Svc.CalcEngine.cs")) { using (StreamReader reader = new StreamReader(stream)) { source = reader.ReadToEnd(); } } // добавление членов класса CalcEngine int todoInd = source.IndexOf("/*TODO*/"); if (todoInd >= 0) { StringBuilder sourceSB = new StringBuilder(source); sourceSB.Remove(todoInd, "/*TODO*/".Length); for (int i = exprList.Count - 1; i >= 0; i--) { string expr = exprList[i]; sourceSB.Insert(todoInd, expr); if (i > 0) { sourceSB.Insert(todoInd, "\r\n"); } } source = sourceSB.ToString(); } // сохранение исходного кода класса CalcEngine в файле для анализа string sourceFileName = mainLogic.AppDirs.LogDir + "CalcEngine.cs"; File.WriteAllText(sourceFileName, source, Encoding.UTF8); // компилирование исходного кода класса CalcEngine CompilerParameters compParams = new CompilerParameters(); compParams.GenerateExecutable = false; compParams.GenerateInMemory = true; compParams.IncludeDebugInformation = false; compParams.ReferencedAssemblies.Add("System.dll"); compParams.ReferencedAssemblies.Add(mainLogic.AppDirs.ExeDir + "ScadaData.dll"); CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp"); CompilerResults compilerResults = compiler.CompileAssemblyFromSource(compParams, source); if (compilerResults.Errors.HasErrors) { appLog.WriteAction(Localization.UseRussian ? "Ошибка при компилировании исходного кода формул: " : "Error compiling the source code of the formulas: ", Log.ActTypes.Error); foreach (CompilerError error in compilerResults.Errors) { appLog.WriteLine(string.Format(Localization.UseRussian ? "Строка {0}, колонка {1}: error {2}: {3}" : "Line {0}, column {1}: error {2}: {3}", error.Line, error.Column, error.ErrorNumber, error.ErrorText)); } appLog.WriteLine(string.Format(Localization.UseRussian ? "Для ознакомления с исходным кодом см. файл {0}" : "See the file {0} with the source code", sourceFileName)); return(false); } else { Type calcEngineType = compilerResults.CompiledAssembly.GetType("Scada.Server.Svc.CalcEngine", true); calcEngine = Activator.CreateInstance(calcEngineType, new Func <int, SrezTableLight.CnlData>(mainLogic.GetProcSrezCnlData)); appLog.WriteAction(Localization.UseRussian ? "Исходный код формул калькулятора откомпилирован" : "The formulas source code has been compiled", Log.ActTypes.Action); return(true); } } catch (Exception ex) { appLog.WriteAction((Localization.UseRussian ? "Ошибка при компилировании исходного кода формул: " : "Error compiling the source code of the formulas: ") + ex.Message, Log.ActTypes.Exception); return(false); } }
private Assembly CompileInMemoryAssembly() { List <string> finalReferenceList = new List <string>(); this.CombineReferencedAssemblies(finalReferenceList); string[] strArray = this.CombineUsingNamespaces(); using (CodeDomProvider provider = CodeDomProvider.CreateProvider(this.language)) { if (provider is CSharpCodeProvider) { this.AddReferenceAssemblyToReferenceList(finalReferenceList, "System"); } CompilerParameters parameters = new CompilerParameters(finalReferenceList.ToArray()) { IncludeDebugInformation = true, GenerateInMemory = true, GenerateExecutable = false }; StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb, CultureInfo.CurrentCulture); CodeGeneratorOptions options = new CodeGeneratorOptions { BlankLinesBetweenMembers = true, VerbatimOrder = true }; CodeCompileUnit compileUnit = new CodeCompileUnit(); if (this.sourcePath != null) { this.sourceCode = File.ReadAllText(this.sourcePath); } string sourceCode = this.sourceCode; if (this.typeIsFragment || this.typeIsMethod) { CodeTypeDeclaration codeTypeDeclaration = this.CreateTaskClass(); this.CreateTaskProperties(codeTypeDeclaration); if (this.typeIsFragment) { CreateExecuteMethodFromFragment(codeTypeDeclaration, this.sourceCode); } else { CreateTaskBody(codeTypeDeclaration, this.sourceCode); } CodeNamespace namespace2 = new CodeNamespace("InlineCode"); foreach (string str2 in strArray) { namespace2.Imports.Add(new CodeNamespaceImport(str2)); } namespace2.Types.Add(codeTypeDeclaration); compileUnit.Namespaces.Add(namespace2); provider.GenerateCodeFromCompileUnit(compileUnit, writer, options); } else { provider.GenerateCodeFromStatement(new CodeSnippetStatement(this.sourceCode), writer, options); } sourceCode = sb.ToString(); CompilerResults results = provider.CompileAssemblyFromSource(parameters, new string[] { sourceCode }); string path = null; if ((results.Errors.Count > 0) || (Environment.GetEnvironmentVariable("MSBUILDLOGCODETASKFACTORYOUTPUT") != null)) { string tempPath = Path.GetTempPath(); string str5 = "MSBUILDCodeTaskFactoryGeneratedFile" + Guid.NewGuid().ToString() + ".txt"; path = Path.Combine(tempPath, str5); File.WriteAllText(path, sourceCode); } if ((results.NativeCompilerReturnValue != 0) && (results.Errors.Count > 0)) { this.log.LogErrorWithCodeFromResources("CodeTaskFactory.FindSourceFileAt", new object[] { path }); foreach (CompilerError error in results.Errors) { this.log.LogErrorWithCodeFromResources("CodeTaskFactory.CompilerError", new object[] { error.ToString() }); } return(null); } return(results.CompiledAssembly); } }
public void Save(string filename) { if (File.Exists(filename)) { File.Delete(filename); } // Issue 10 - Update the code to Net Framework 3.5 - http://code.google.com/p/pandorasbox3/issues/detail?id=10 - Smjert List <string> embedded = new List <string>(); List <string> files = new List <string>(); // Issue 10 - End embedded.Add("BoxData.xml"); files.Add(Path.Combine(m_Profile.BaseFolder, "BoxData.xml")); embedded.Add("PropsData.xml"); files.Add(Path.Combine(m_Profile.BaseFolder, "PropsData.xml")); embedded.Add("HueGroups.xml"); files.Add(Path.Combine(m_Profile.BaseFolder, "HueGroups.xml")); embedded.Add("RandomTiles.xml"); files.Add(Path.Combine(m_Profile.BaseFolder, "RandomTiles.xml")); embedded.Add("Skills.ini"); files.Add(Path.Combine(m_Profile.BaseFolder, "Skills.ini")); if (File.Exists(Path.Combine(m_Profile.BaseFolder, "SpawnData.xml"))) { embedded.Add("SpawnData.xml"); files.Add(Path.Combine(m_Profile.BaseFolder, "SpawnData.xml")); } if (File.Exists(Path.Combine(m_Profile.BaseFolder, "SpawnGroups.xml"))) { embedded.Add("SpawnGroups.xml"); files.Add(Path.Combine(m_Profile.BaseFolder, "SpawnGroups.xml")); } MapIndex = embedded.Count; for (int i = 0; i < 4; i++) { string xml = Path.Combine(m_Profile.BaseFolder, Path.Combine("Locations", string.Format("map{0}.xml", i))); string small = Path.Combine(m_Profile.BaseFolder, Path.Combine("Maps", string.Format("map{0}small.jpg", i))); string big = Path.Combine(m_Profile.BaseFolder, Path.Combine("Maps", string.Format("map{0}big.jpg", i))); if (File.Exists(xml)) { embedded.Add(Path.GetFileName(xml)); files.Add(xml); } if (File.Exists(small)) { embedded.Add(Path.GetFileName(small)); files.Add(small); } if (File.Exists(big)) { embedded.Add(Path.GetFileName(big)); files.Add(big); } } ButtonIndex = embedded.Count; if (ButtonIndex == MapIndex) { MapIndex = -1; } if (Directory.Exists(Path.Combine(m_Profile.BaseFolder, "Buttons"))) { string[] buttons = Directory.GetFiles(Path.Combine(m_Profile.BaseFolder, "Buttons")); foreach (string b in buttons) { embedded.Add(Path.GetFileName(b)); files.Add(b); } } EmbeddedList = new string[embedded.Count]; if (EmbeddedList.Length == ButtonIndex) { ButtonIndex = -1; } string temp = Path.Combine(Pandora.Folder, "temp.xml"); // Build the string with all the embedded resources string res = string.Format("/resource:\"{0}\",{1}", temp, "ProfileIO.xml"); for (int i = 0; i < embedded.Count; i++) { res += " "; // Issue 10 - Update the code to Net Framework 3.5 - http://code.google.com/p/pandorasbox3/issues/detail?id=10 - Smjert res += string.Format("/resource:\"{0}\",{1}", files[i], embedded[i]); EmbeddedList[i] = embedded[i]; // Issue 10 - End } if (!TheBox.Common.Utility.SaveXml(this, temp)) { Pandora.Log.WriteError(null, "Couldn't export profile {0}", m_Profile.Name); System.Windows.Forms.MessageBox.Show("An error occurred, export failed."); return; } // Issue 3 - Obsolete interface - Useless code - http://code.google.com/p/pandorasbox3/issues/detail?id=3&can=1 - Kons CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp"); // Issue 3 - End CompilerParameters options = new CompilerParameters(); options.CompilerOptions = res; options.GenerateExecutable = false; options.IncludeDebugInformation = false; options.OutputAssembly = filename; CompilerResults err = compiler.CompileAssemblyFromSource(options, "//Empty"); if (File.Exists(filename)) { FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); byte[] data = new byte[fStream.Length]; fStream.Read(data, 0, (int)fStream.Length); fStream.Close(); File.Delete(filename); // Issue 4: Profile Exporting does not work - Tarion byte[] compressed = null; try { compressed = TheBox.Common.BoxZLib.Compress(data); } catch { System.Windows.Forms.MessageBox.Show("Missing zlib.dll, can not export profile.", "Missing library", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } // End Issue 4: if (compressed != null) { FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read); fs.Write(compressed, 0, compressed.Length); fs.Close(); Pandora.Log.WriteEntry("Profile {0} exported to {1}", m_Profile.Name, filename); } } if (File.Exists(temp)) { File.Delete(temp); } }
public bool CompileExecutable(String fileContents, String fileName, SourceFileType fileType, out Assembly compiledAssemply) { compiledAssemply = null; // TODO: look into Managed Extensibility Framework CodeDomProvider provider = null; bool compileOk = false; // Select the code provider based on the input file extension. if (fileType == SourceFileType.CSharp) { provider = CodeDomProvider.CreateProvider("CSharp"); } else if (fileType == SourceFileType.VisualBasic) { provider = CodeDomProvider.CreateProvider("VisualBasic"); } else { Debug.WriteLine("Source file must have a .cs or .vb extension"); } if (provider != null) { // Format the executable file name. // Build the output assembly path using the current directory // and <source>_cs.exe or <source>_vb.exe. CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("MatterHackers.Csg.dll"); cp.ReferencedAssemblies.Add("MatterHackers.VectorMath.dll"); // Generate an executable instead of // a class library. cp.GenerateExecutable = false; // Save the assembly as a physical file. cp.GenerateInMemory = true; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Invoke compilation of the source file. //CompilerResults cr = provider.CompileAssemblyFromFile(cp, fileName); CompilerResults cr = provider.CompileAssemblyFromSource(cp, fileContents); if (cr.Errors.Count > 0) { // Display compilation errors. foreach (CompilerError ce in cr.Errors) { Debug.WriteLine(" {0}", ce.ToString()); Debug.WriteLine(""); } } else { // Display a successful compilation message. Debug.WriteLine("Source built successfully."); } // Return the results of the compilation. if (cr.Errors.Count > 0) { compileOk = false; } else { compileOk = true; } compiledAssemply = cr.CompiledAssembly; } return(compileOk); }
public override void Bad(HttpRequest req, HttpResponse resp) { string data; if (IO.StaticReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Read data from a querystring using Params.Get */ data = req.Params.Get("name"); } else { /* FIX: Set data to an integer represented as a string */ data = "10"; } if (IO.StaticReturnsTrueOrFalse()) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); /* POTENTIAL FLAW: Compile sourceCode containing unvalidated user input */ CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } else { int?parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } } }
///<remarks>Brendan Ingram has greatly improved this method.</remarks> private static object LoadClass(CodeDomProvider codeProvider, string targetClassName, string source, bool sourceIsString) { CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = Compilation.GenerateInMemoryAssembly; compilerParameters.IncludeDebugInformation = true; compilerParameters.TreatWarningsAsErrors = false; compilerParameters.CompilerOptions = compilerOptions; // Chuck Cross has vastly improved the loading of NxBRE DLL reference mechanism bool nxbreAssemblyLoaded = false; // Add all implicitly referenced assemblies if ((ReferenceLinkMode == ReferenceLinkModes.CurrentDomain) || (ReferenceLinkMode == ReferenceLinkModes.Full)) { foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { // do not add AssemblyBuilders (bug 1482753), thanks to Bob Brumfield // handle .NET4 dynamic assemblies correctly, thanks to Nich if (!(assembly is AssemblyBuilder) && (assembly.ManifestModule.GetType().Namespace != "System.Reflection.Emit")) { AddReferencedAssembly(compilerParameters, assembly.Location); if (assembly.ManifestModule.ScopeName.Equals(NXBRE_DLL)) { nxbreAssemblyLoaded = true; } } } } // Add NxBRE DLL reference only if not already added through implicit references. if (!nxbreAssemblyLoaded && ((ReferenceLinkMode == ReferenceLinkModes.NxBRE) || (ReferenceLinkMode == ReferenceLinkModes.Full))) { AddReferencedAssembly(compilerParameters, NxBREAssemblyLocation); } // Add any extra DLL listed in the application configuration String extraReferences = Parameter.GetString("extraReferences"); if (extraReferences != null) { foreach (String dllToReference in extraReferences.Split(';')) { AddReferencedAssembly(compilerParameters, dllToReference); } } CompilerResults cr; if (sourceIsString) { cr = codeProvider.CompileAssemblyFromSource(compilerParameters, source); } else { cr = codeProvider.CompileAssemblyFromFile(compilerParameters, source); } if (cr.Errors.Count != 0) { throw new BREException(GetCompilerErrors(cr)); } // Marcin Kielar - zorba128 // Under some (strange?) conditions, compilation finishes without errors, // but assembly cannot be loaded: // - any of Assembly's methods (here - GetTypes) throws exception // - CreateInstance returns null try { cr.CompiledAssembly.GetTypes(); } catch (Exception e) { throw new BREException("Unable to create evaluator class instance - assembly loading problem", e); } object evaluatorInstance = cr.CompiledAssembly.CreateInstance(targetClassName); if (evaluatorInstance == null) { throw new BREException("Unable to create evaluator class instance"); } return(evaluatorInstance); }
/// <summary> /// Compile the assembly in memory and get a reference to the assembly itself. /// If compilation fails, returns null. /// </summary> private Assembly CompileInMemoryAssembly() { // Combine our default assembly references with those specified var finalReferencedAssemblies = new List <string>(); CombineReferencedAssemblies(finalReferencedAssemblies); // Combine our default using's with those specified string[] finalUsingNamespaces = CombineUsingNamespaces(); // Language can be anything that has a codedom provider, in the standard naming method // "c#;cs;csharp", "vb;vbs;visualbasic;vbscript", "js;jscript;javascript", "vj#;vjs;vjsharp", "c++;mc;cpp" using (CodeDomProvider provider = CodeDomProvider.CreateProvider(_language)) { if (provider is CSharp.CSharpCodeProvider) { AddReferenceAssemblyToReferenceList(finalReferencedAssemblies, "System"); } var compilerParameters = new CompilerParameters(finalReferencedAssemblies.ToArray()) { // We don't need debug information IncludeDebugInformation = true, // Not a file based assembly GenerateInMemory = true, // Indicates that a .dll should be generated. GenerateExecutable = false }; // Horrible code dom / compilation declarations var codeBuilder = new StringBuilder(); var writer = new StringWriter(codeBuilder, CultureInfo.CurrentCulture); var codeGeneratorOptions = new CodeGeneratorOptions { BlankLinesBetweenMembers = true, VerbatimOrder = true }; var compilationUnit = new CodeCompileUnit(); // If our code is in a separate file, then read it in here if (_sourcePath != null) { _sourceCode = File.ReadAllText(_sourcePath); } // A fragment is essentially the contents of the execute method (except the final return true/false) // A method is the whole execute method specified // Anything else assumes that the whole class is being supplied if (_typeIsFragment || _typeIsMethod) { CodeTypeDeclaration codeTypeDeclaration = CreateTaskClass(); CreateTaskProperties(codeTypeDeclaration); if (_typeIsFragment) { CreateExecuteMethodFromFragment(codeTypeDeclaration, _sourceCode); } else { CreateTaskBody(codeTypeDeclaration, _sourceCode); } var codeNamespace = new CodeNamespace("InlineCode"); foreach (string importname in finalUsingNamespaces) { codeNamespace.Imports.Add(new CodeNamespaceImport(importname)); } codeNamespace.Types.Add(codeTypeDeclaration); compilationUnit.Namespaces.Add(codeNamespace); // Create the source for the CodeDom provider.GenerateCodeFromCompileUnit(compilationUnit, writer, codeGeneratorOptions); } else { // We are a full class, so just create the CodeDom from the source provider.GenerateCodeFromStatement(new CodeSnippetStatement(_sourceCode), writer, codeGeneratorOptions); } // Our code generation is complete, grab the source from the builder ready for compilation string fullCode = codeBuilder.ToString(); var fullSpec = new FullTaskSpecification(finalReferencedAssemblies, fullCode); if (!s_compiledTaskCache.TryGetValue(fullSpec, out Assembly existingAssembly)) { // Invokes compilation. // Note: CompileAssemblyFromSource uses Path.GetTempPath() directory, but will not create it. In some cases // this will throw inside CompileAssemblyFromSource. To work around this, ensure the temp directory exists. // See: https://github.com/Microsoft/msbuild/issues/328 Directory.CreateDirectory(Path.GetTempPath()); CompilerResults compilerResults = provider.CompileAssemblyFromSource(compilerParameters, fullCode); string outputPath = null; if (compilerResults.Errors.Count > 0 || Environment.GetEnvironmentVariable("MSBUILDLOGCODETASKFACTORYOUTPUT") != null) { string tempDirectory = Path.GetTempPath(); string fileName = Guid.NewGuid().ToString() + ".txt"; outputPath = Path.Combine(tempDirectory, fileName); File.WriteAllText(outputPath, fullCode); } if (compilerResults.NativeCompilerReturnValue != 0 && compilerResults.Errors.Count > 0) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.FindSourceFileAt", outputPath); foreach (CompilerError e in compilerResults.Errors) { _log.LogErrorWithCodeFromResources("CodeTaskFactory.CompilerError", e.ToString()); } return(null); } // Add to the cache. Failing to add is not a fatal error. s_compiledTaskCache.TryAdd(fullSpec, compilerResults.CompiledAssembly); return(compilerResults.CompiledAssembly); } else { return(existingAssembly); } } }
/* goodB2G() - use badsource and goodsink */ private void GoodB2G() { string dataCopy; { string data; data = ""; /* Initialize data */ /* Read data using a listening tcp connection */ { TcpListener listener = null; try { listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543); listener.Start(); using (TcpClient tcpConn = listener.AcceptTcpClient()) { /* read input from socket */ using (StreamReader sr = new StreamReader(tcpConn.GetStream())) { /* POTENTIAL FLAW: Read data using a listening tcp connection */ data = sr.ReadLine(); } } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } finally { if (listener != null) { try { listener.Stop(); } catch (SocketException se) { IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener"); } } } } dataCopy = data; } { string data = dataCopy; int? parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } } }
public static object Compile(string source) { CompilerParameters opts = new CompilerParameters(); opts.GenerateInMemory = true; opts.TreatWarningsAsErrors = false; opts.GenerateExecutable = false; opts.ReferencedAssemblies.Add(typeof(ScriptManager).Assembly.Location); opts.ReferencedAssemblies.AddRange(DefaultRefs.Select(r => File.Exists(r) ? Path.Combine(Environment.CurrentDirectory, r) : r).ToArray()); opts.ReferencedAssemblies.AddRange(Directory.GetFiles(".", "*.dll").Select(x => Path.Combine(Environment.CurrentDirectory, x)).Where(CanLoadAssembly).ToArray()); if (Directory.Exists("plugins")) { opts.ReferencedAssemblies.AddRange(Directory.GetFiles("plugins", "*.dll").Select(x => Path.Combine(Environment.CurrentDirectory, x)).Where(CanLoadAssembly).ToArray()); } foreach (string line in source.Split('\n').Select(l => l.Trim())) { if (line.StartsWith("using")) { break; } if (line.StartsWith("//cs_")) { string[] parts = line.Split((char[])null, 2, StringSplitOptions.RemoveEmptyEntries); string cmd = parts[0].Substring(5); switch (cmd) { case "ref": string local = Path.Combine(Environment.CurrentDirectory, parts[1]); if (File.Exists(local)) { opts.ReferencedAssemblies.Add(local); } else { opts.ReferencedAssemblies.Add(parts[1]); } break; } } } CompilerResults results = _provider.CompileAssemblyFromSource(opts, source); if (results.Errors.Count == 0) { Type t = results.CompiledAssembly.DefinedTypes.First(t => t.GetDeclaredMethod("ScriptMain") != null); if (t == null) { throw new Exception("No declared type with entry point found."); } return(Activator.CreateInstance(t)); } else { StringBuilder sb = new StringBuilder(); foreach (CompilerError error in results.Errors) { sb.AppendLine(error.ToString()); } throw new ScriptCompileException(sb.ToString()); } }
/* goodB2G() - use badsource and goodsink */ private void GoodB2G() { string data; data = ""; /* Initialize data */ /* Read data from a database */ { try { /* setup the connection */ using (SqlConnection connection = IO.GetDBConnection()) { connection.Open(); /* prepare and execute a (hardcoded) query */ using (SqlCommand command = new SqlCommand(null, connection)) { command.CommandText = "select name from users where id=0"; command.Prepare(); using (SqlDataReader dr = command.ExecuteReader()) { /* POTENTIAL FLAW: Read data from a database query SqlDataReader */ data = dr.GetString(1); } } } } catch (SqlException exceptSql) { IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error with SQL statement"); } } int?parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } }
public static void InterpretIf(string Condition, Dictionary <string, object> Variables, out bool ConditionMet, out bool Error, out string ErrorText) { Error = false; ErrorText = ""; ConditionMet = false; if (CleanCode(Condition) == false) { Error = true; ErrorText = "Invalid code"; ConditionMet = false; Debug.WriteLine("Invalid code"); return; } CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); cp.GenerateInMemory = true; cp.IncludeDebugInformation = false; cp.TreatWarningsAsErrors = false; string source = ""; source += "using System;\r\n"; source += "\r\n"; source += "public class iftest {\r\n"; source += "public bool Test(){\r\n"; foreach (KeyValuePair <string, object> kvp in Variables) { if (kvp.Value.GetType() == typeof(string)) { source += "string " + kvp.Key + "=@\"" + ((string)kvp.Value).Replace("\"", "\"\"") + "\";\r\n"; } if (kvp.Value.GetType() == typeof(int)) { source += "int " + kvp.Key + "=" + ((int)kvp.Value).ToString() + ";\r\n"; } if (kvp.Value.GetType() == typeof(Int64)) { source += "Int64 " + kvp.Key + "=" + ((Int64)kvp.Value).ToString() + ";\r\n"; } if (kvp.Value.GetType() == typeof(DateTime)) { DateTime DT = (DateTime)kvp.Value; source += "DateTime " + kvp.Key + "= new DateTime(" + DT.Year.ToString() + "," + DT.Month.ToString() + "," + DT.Day.ToString() + "," + DT.Hour.ToString() + "," + DT.Minute.ToString() + "," + DT.Second.ToString() + "," + DT.Millisecond.ToString() + ");\r\n"; } } source += "if (" + Condition + ")\r\nreturn(true);\r\nelse\r\nreturn(false);\r\n}}\r\n"; Debug.WriteLine(source); CompilerResults cr = provider.CompileAssemblyFromSource(cp, source); if (cr.Errors.Count > 0) { foreach (CompilerError ce in cr.Errors) { Debug.WriteLine(ce.ToString()); ErrorText += ce.ToString() + "\r\n"; } ConditionMet = false; Error = true; return; } try { object o = cr.CompiledAssembly.CreateInstance("iftest"); Type type = o.GetType(); bool ret = (bool)type.InvokeMember("Test", BindingFlags.InvokeMethod | BindingFlags.Default, null, o, null); ConditionMet = ret; } catch (Exception ee) { Debug.WriteLine(ee.ToString()); ErrorText = "SEH Error"; ConditionMet = false; Error = true; return; } }
public void compile(string path) { string basecode = Properties.Resources.Code; basecode = BuildBase(basecode); List <string> code = new List <string>(); code.Add(basecode); string manifest = @"<?xml version=""1.0"" encoding=""utf-8""?> <assembly manifestVersion=""1.0"" xmlns=""urn:schemas-microsoft-com:asm.v1""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""highestAvailable"" uiAccess=""false"" /> </requestedPrivileges> </security> </trustInfo> <compatibility xmlns=""urn:schemas-microsoft-com:compatibility.v1""> <application> </application> </compatibility> </assembly> "; File.WriteAllText(Application.StartupPath + @"\manifest.manifest", manifest); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters compars = new CompilerParameters(); compars.ReferencedAssemblies.Add("System.Net.dll"); compars.ReferencedAssemblies.Add("System.Net.Http.dll"); compars.ReferencedAssemblies.Add("System.dll"); compars.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compars.ReferencedAssemblies.Add("System.Drawing.dll"); compars.ReferencedAssemblies.Add("System.Management.dll"); compars.ReferencedAssemblies.Add("System.IO.dll"); compars.ReferencedAssemblies.Add("System.IO.compression.dll"); compars.ReferencedAssemblies.Add("System.IO.compression.filesystem.dll"); compars.ReferencedAssemblies.Add("System.Core.dll"); compars.ReferencedAssemblies.Add("System.Security.dll"); compars.ReferencedAssemblies.Add("System.Diagnostics.Process.dll"); string ospath = Path.GetPathRoot(Environment.SystemDirectory); string tempPath = ospath + "Temp"; try { Directory.CreateDirectory(tempPath); File.Delete(tempPath + "\\ConfuserEx.zip"); Directory.Delete(tempPath + "ConfuserEx", true); File.Delete(Path.GetDirectoryName(path) + "\\Names.txt"); } catch { } File.WriteAllBytes(tempPath + "\\ConfuserEx.zip", Properties.Resources.ConfuserEx); ZipFile.ExtractToDirectory(tempPath + "\\ConfuserEx.zip", tempPath + "\\ConfuserEx"); string crprojCode = string.Join( Environment.NewLine, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "<project outputDir=\"" + Path.GetDirectoryName(path) + "\" baseDir=\"" + Path.GetDirectoryName(path) + "\" xmlns=\"http://confuser.codeplex.com\">", " <rule pattern=\"true\" inherit=\"false\">", " <protection id=\"anti de4dot\" />", " <protection id=\"anti ildasm\" />", " <protection id=\"anti tamper\" />", " <protection id=\"anti watermark\" />", " <protection id=\"constant mutate\" />", " <protection id=\"constants\" />", " <protection id=\"ctrl flow\" />", " <protection id=\"integrity prot\" />", " <protection id=\"invalid metadata\" />", " <protection id=\"invalid cctor\" />", " <protection id=\"junk\" />", " <protection id=\"module properties\" />", " <protection id=\"opcode prot\" />", " <protection id=\"reduce md\" />", " <protection id=\"ref proxy\" />", " <protection id=\"stack underflow\" />", " <protection id=\"rename\" />", " </rule>", " <module path=\"" + Path.GetFileName(path) + "\" />", "</project>" ); File.WriteAllText(tempPath + @"\ConfuserEx\198v2\obf.crproj", crprojCode); File.Copy(tempPath + @"\ConfuserEx\198v2\Names.txt", Path.GetDirectoryName(path) + "\\Names.txt"); compars.GenerateExecutable = true; compars.OutputAssembly = path; compars.GenerateInMemory = false; compars.TreatWarningsAsErrors = false; compars.CompilerOptions += "/t:winexe /unsafe /platform:x86"; if (!string.IsNullOrEmpty(metroTextBox7.Text) || !string.IsNullOrWhiteSpace(metroTextBox7.Text) && metroTextBox7.Text.Contains(@"\") && metroTextBox7.Text.Contains(@":") && metroTextBox7.Text.Length >= 7) { compars.CompilerOptions += " /win32icon:" + @"""" + metroTextBox7.Text + @""""; } else if (string.IsNullOrEmpty(metroTextBox7.Text) || string.IsNullOrWhiteSpace(metroTextBox7.Text)) { } System.Threading.Thread.Sleep(100); CompilerResults res = provider.CompileAssemblyFromSource(compars, code.ToArray()); if (res.Errors.Count > 0) { try { File.Delete(Application.StartupPath + @"\manifest.manifest"); } catch { } foreach (CompilerError ce in res.Errors) { MessageBox.Show(ce.ToString()); } } else { try { File.Delete(Application.StartupPath + @"\manifest.manifest"); } catch { } Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.WorkingDirectory = tempPath + @"\ConfuserEx\198v2"; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.StartInfo.Arguments = "/C Confuser.CLI obf.crproj"; p.Start(); p.WaitForExit(); try { File.Delete(tempPath + @"\ConfuserEx.zip"); Directory.Delete(tempPath + @"\ConfuserEx", true); File.Delete(Path.GetDirectoryName(path) + "\\Names.txt"); } catch { } MessageBox.Show("Stealer compiled!"); } }
public CompilerResults CompileAssemblyFromSource(CompilerParameters parameters, params string[] sources) { return(codeProvider.CompileAssemblyFromSource(parameters, sources)); }
private void InternalCompile() { // set the current folder string currentFolder = Config.ApplicationFolder; if (Config.WebMode) { try { if (Directory.Exists(currentFolder + @"Bin\")) { currentFolder += @"Bin\"; } } catch { } } // Commented by Samuray //Directory.SetCurrentDirectory(currentFolder); // configure compiler options CompilerParameters cp = new CompilerParameters(); AddFastReportAssemblies(cp.ReferencedAssemblies); #if NETCOREAPP cp.ReferencedAssemblies.Add("System.Drawing.Primitives"); #endif AddReferencedAssemblies(cp.ReferencedAssemblies, currentFolder); ReviewReferencedAssemblies(cp.ReferencedAssemblies); cp.GenerateInMemory = true; // sometimes the system temp folder is not accessible... if (Config.TempFolder != null) { cp.TempFiles = new TempFileCollection(Config.TempFolder, false); } // find assembly in cache StringBuilder assemblyHashSB = new StringBuilder(); foreach (string a in cp.ReferencedAssemblies) { assemblyHashSB.Append(a); } assemblyHashSB.Append(scriptText.ToString()); byte[] hash = null; using (HMACSHA1 hMACSHA1 = new HMACSHA1(Encoding.ASCII.GetBytes(shaKey))) { hash = hMACSHA1.ComputeHash(Encoding.Unicode.GetBytes(assemblyHashSB.ToString())); } string assemblyHash = Convert.ToBase64String(hash); Assembly cachedAssembly = null; if (FAssemblyCache.TryGetValue(assemblyHash, out cachedAssembly)) { assembly = cachedAssembly; InitInstance(assembly.CreateInstance("FastReport.ReportScript")); return; } // compile report scripts using (CodeDomProvider provider = Report.CodeHelper.GetCodeProvider()) { ScriptSecurityEventArgs ssea = new ScriptSecurityEventArgs(Report, scriptText.ToString(), Report.ReferencedAssemblies); Config.OnScriptCompile(ssea); CompilerResults cr = provider.CompileAssemblyFromSource(cp, scriptText.ToString()); assembly = null; instance = null; bool needException = true; // shows need to throw exception or errors can be handled without exception if (cr.Errors.Count > 0) { string errors = ""; foreach (CompilerError ce in cr.Errors) { int line = GetScriptLine(ce.Line); // error is inside own items if (line == -1) { string errObjName = GetErrorObjectName(ce.Line); // handle division by zero errors if (ce.ErrorNumber == "CS0020") { TextObjectBase text = Report.FindObject(errObjName) as TextObjectBase; text.CanGrow = true; text.FillColor = Color.Red; text.Text = "DIVISION BY ZERO!"; if (cr.Errors.Count == 1) // there are only division by zero errors, exception does't needed { needException = false; } } else { errors += String.Format("({0}): " + Res.Get("Messages,Error") + " {1}: {2}", new object[] { errObjName, ce.ErrorNumber, ce.ErrorText }) + "\r\n"; ErrorMsg(errObjName, ce); } } else { errors += String.Format("({0},{1}): " + Res.Get("Messages,Error") + " {2}: {3}", new object[] { line, ce.Column, ce.ErrorNumber, ce.ErrorText }) + "\r\n"; ErrorMsg(ce, line); } } if (needException) // throw exception if errors were not handled { throw new CompilerException(errors); } } else { #if DOTNET_4 FAssemblyCache.TryAdd(assemblyHash, cr.CompiledAssembly); #else FAssemblyCache.Add(assemblyHash, cr.CompiledAssembly); #endif assembly = cr.CompiledAssembly; InitInstance(assembly.CreateInstance("FastReport.ReportScript")); } } }
public override void Bad() { string data; if (PrivateReturnsTrue()) { data = ""; /* Initialize data */ /* Read data using a listening tcp connection */ { TcpListener listener = null; try { listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543); listener.Start(); using (TcpClient tcpConn = listener.AcceptTcpClient()) { /* read input from socket */ using (StreamReader sr = new StreamReader(tcpConn.GetStream())) { /* POTENTIAL FLAW: Read data using a listening tcp connection */ data = sr.ReadLine(); } } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } finally { if (listener != null) { try { listener.Stop(); } catch (SocketException se) { IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener"); } } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PrivateReturnsTrue()) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); /* POTENTIAL FLAW: Compile sourceCode containing unvalidated user input */ CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } }
/// <summary> /// Compiles a written function from source into a DLL. /// </summary> /// <param name="commandName">Name of the command file to be compiled (without the extension)</param> /// <returns>True on successful compile, false on failure.</returns> public static bool Compile(string commandName) { string divider = new string('-', 25); if (!File.Exists(sourcepath + "Cmd" + commandName + ".cs")) { bool check = File.Exists("logs/errors/compiler.log"); StreamWriter errlog = new StreamWriter("logs/errors/compiler.log", check); if (check) { errlog.WriteLine(); errlog.WriteLine(divider); errlog.WriteLine(); } errlog.WriteLine("File not found: Cmd" + commandName + ".cs"); errlog.Dispose(); return(false); } if (!Directory.Exists(dllpath)) { Directory.CreateDirectory(dllpath); } parameters.GenerateExecutable = false; parameters.MainClass = commandName; parameters.OutputAssembly = dllpath + "Cmd" + commandName + ".dll"; parameters.ReferencedAssemblies.Add("MCForge_.dll"); StreamReader sr = new StreamReader(sourcepath + "cmd" + commandName + ".cs"); results = compiler.CompileAssemblyFromSource(parameters, sr.ReadToEnd().Replace("namespace MCLawl", "namespace MCForge")); sr.Dispose(); switch (results.Errors.Count) { case 0: return(true); case 1: CompilerError error = results.Errors[0]; bool exists = (File.Exists("logs/errors/compiler.log")) ? true : false; StringBuilder sb = new StringBuilder(); if (exists) { sb.AppendLine(); sb.AppendLine(divider); sb.AppendLine(); } sb.AppendLine("Error " + error.ErrorNumber); sb.AppendLine("Message: " + error.ErrorText); sb.AppendLine("Line: " + error.Line); StreamWriter sw = new StreamWriter("logs/errors/compiler.log", exists); sw.Write(sb.ToString()); sw.Dispose(); return(false); default: exists = (File.Exists("logs/errors/compiler.log")) ? true : false; sb = new StringBuilder(); bool start = true; if (exists) { sb.AppendLine(); sb.AppendLine(divider); sb.AppendLine(); } foreach (CompilerError err in results.Errors) { if (!start) { sb.AppendLine(); sb.AppendLine(divider); sb.AppendLine(); } sb.AppendLine("Error #" + err.ErrorNumber); sb.AppendLine("Message: " + err.ErrorText); sb.AppendLine("Line: " + err.Line); if (start) { start = false; } } sw = new StreamWriter("logs/errors/compiler.log", exists); sw.Write(sb.ToString()); sw.Dispose(); return(false); } }
/// <summary> /// 解析字符串构造函数 /// </summary> /// <param name="items">待解析字符串数组</param> private void ConstructEvaluator(EvaluatorItem[] items) { //创建C#编译器实例 CodeDomProvider provider = CodeDomProvider.CreateProvider("C#"); //过时了 //ICodeCompiler comp = provider.CreateCompiler(); //编译器的传入参数 _compilerParameters.ReferencedAssemblies.Add("system.dll"); //添加程序集 system.dll 的引用 _compilerParameters.ReferencedAssemblies.Add("system.data.dll"); //添加程序集 system.data.dll 的引用 _compilerParameters.ReferencedAssemblies.Add("system.xml.dll"); //添加程序集 system.xml.dll 的引用 _compilerParameters.GenerateExecutable = false; //不生成可执行文件 _compilerParameters.GenerateInMemory = true; //在内存中运行 StringBuilder code = new StringBuilder(); //创建代码串 /* * 添加常见且必须的引用字符串 */ code.AppendLine("using System; "); code.AppendLine("using System.Data; "); code.AppendLine("using System.Data.SqlClient; "); code.AppendLine("using System.Data.OleDb; "); code.AppendLine("using System.Xml; "); foreach (var item in _extraNamespaces) { code.AppendLine(item); } code.AppendLine("namespace Granda.IZ.CodeDom { "); //生成代码的命名空间为Granda.IZ.CodeDom code.AppendLine(" public class _Evaluator { "); //产生 _Evaluator 类,所有可执行代码均在此类中运行 foreach (EvaluatorItem item in items) //遍历每一个可执行字符串项 { code.AppendFormat(" public {0} {1}() ", //添加定义公共函数代码 item.ReturnType.Name, //函数返回值为可执行字符串项中定义的返回值类型 item.Name); //函数名称为可执行字符串项中定义的执行字符串名称 code.AppendLine("{ "); //添加函数开始括号 code.AppendFormat("return ({0});", item.Expression); //添加函数体,返回可执行字符串项中定义的表达式的值 code.AppendLine("}"); //添加函数结束括号 } code.AppendLine("} }"); //添加类结束和命名空间结束括号 //得到编译器实例的返回结果 CompilerResults cr = provider.CompileAssemblyFromSource(_compilerParameters, code.ToString()); //comp if (cr.Errors.HasErrors) //如果有错误 { StringBuilder error = new StringBuilder(); //创建错误信息字符串 error.AppendLine("编译有错误的表达式: "); //添加错误文本 foreach (CompilerError err in cr.Errors) //遍历每一个出现的编译错误 { error.AppendFormat("{0}", err.ErrorText); //添加进错误文本,每个错误后换行 } throw new Exception("编译错误: " + error.ToString()); //抛出异常 } Assembly a = cr.CompiledAssembly; //获取编译器实例的程序集 _Compiled = a.CreateInstance("Granda.IZ.CodeDom._Evaluator"); //通过程序集查找并声明 Granda.IZ.CodeDom._Evaluator 的实例 }
public static string EvaluateString(string strToEvaluate, Dictionary <string, object> props = null) { try { using (CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp")) { CompilerParameters cp = new CompilerParameters(); string className = "Class" + System.Guid.NewGuid().ToString().Replace("-", ""); cp.ReferencedAssemblies.Add("system.dll"); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append("using System;\n"); sb.Append("using System.Collections.Generic;\n"); sb.Append("namespace EasyObject.Evaluator { \n"); sb.Append("\tpublic class " + className + "{ \n"); if (props != null) { foreach (KeyValuePair <string, object> kvPair in props) { sb.AppendFormat("\t\t{0} {1};\n", kvPair.Value.GetType().Name, kvPair.Key); } } sb.Append("\t\tpublic object Evaluate(object props = null){\n"); if (props != null) { sb.Append("\t\t\tif ((props !=null) && (props is Dictionary<string,object>)){\n"); foreach (KeyValuePair <string, object> kvPair in props) { sb.AppendFormat("\t\t\t\t{1} = ({0})((Dictionary<string,object>)props)[\"{1}\"]; \n", kvPair.Value.GetType().Name, kvPair.Key); } sb.Append("\t\t\t}\n"); } sb.Append("\t\t\treturn " + strToEvaluate + "; \n"); sb.Append("\t\t} \n"); sb.Append("\t} \n"); sb.Append("}\n"); CompilerResults cr = codeProvider.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { return(strToEvaluate); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("EasyObject.Evaluator." + className); Type t = o.GetType(); MethodInfo mi = t.GetMethod("Evaluate"); object s = String.Empty; s = mi.Invoke(o, new object[] { props }); return(s.ToString()); } } catch { return(strToEvaluate); } }
public object createClassOnTheFly(string data) { string[] lines = data.Split('\n'); //1: read types string[] identifiers = lines[0].Split(split); string[] typesToRead = lines[1].Split(split); string[] theTypes = new string[typesToRead.Length]; for (int i = 0; i < typesToRead.Length; i++) { if (isBool(typesToRead[i])) { theTypes[i] = "bool"; } else if (isFloat(typesToRead[i])) { theTypes[i] = "float"; } else { theTypes[i] = "string"; } } string DataObject = createClass(identifiers, theTypes); Debug.Log(DataObject); //compile the class CodeDomProvider oCodeDomProvider = CodeDomProvider.CreateProvider("CSharp"); // Add what referenced assemblies CompilerParameters oCompilerParameters = new CompilerParameters(); oCompilerParameters.ReferencedAssemblies.Add("system.dll"); // set the compiler to create a DLL oCompilerParameters.GenerateExecutable = false; // set the dll to be created in memory and not on the hard drive oCompilerParameters.GenerateInMemory = true; var oCompilerResults = oCodeDomProvider.CompileAssemblyFromSource(oCompilerParameters, DataObject); if (oCompilerResults.Errors.Count != 0) { Debug.Log("There were errors while compiling the Data "); } var oAssembly = oCompilerResults.CompiledAssembly; object oObject = oAssembly.CreateInstance("DataObject"); Type _DataStructureType = oObject.GetType(); //Debug.Log(GetPropValue(oObject,"CerealName")); FieldInfo[] fi = oObject.GetType().GetFields(); foreach (FieldInfo info in fi) { Debug.Log(info.Name + " is type of " + info.FieldType.Name); } //create the datastructure for (int i = 1; i < lines.Length - 1; i++) { string[] values = lines[i].Split(','); object DataStructure = Activator.CreateInstance(_DataStructureType); } return(oObject); }
public object Run(string in_lang, string in_source) { string tempPath = System.IO.Path.GetTempPath() + "DotNET-Script-Tmp"; try { if (!CodeDomProvider.IsDefinedLanguage(in_lang)) { // No provider defined for this language string sMsg = "No compiler is defined for " + in_lang; Console.WriteLine(sMsg); return(null); } CodeDomProvider compiler = CodeDomProvider.CreateProvider(in_lang); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.OutputAssembly = tempPath; parameters.MainClass = "Script.Main"; parameters.IncludeDebugInformation = false; parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Core.dll"); parameters.ReferencedAssemblies.Add("System.Data.dll"); parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll"); parameters.ReferencedAssemblies.Add("System.Xaml.dll"); parameters.ReferencedAssemblies.Add("System.Xml.dll"); parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll"); parameters.GenerateInMemory = true; string dotNetSDKPath = AppDomain.CurrentDomain.BaseDirectory; parameters.ReferencedAssemblies.Add(dotNetSDKPath + "openmayacs.dll"); CompilerResults results = compiler.CompileAssemblyFromSource(parameters, in_source); if (results.Errors.Count > 0) { string sErrors = "Search Condition is invalid:\n"; foreach (CompilerError err in results.Errors) { sErrors += err.ToString() + "\n"; } MessageBox.Show(sErrors, "DAG Explorer", MessageBoxButton.OK, MessageBoxImage.Error); } else { object o = results.CompiledAssembly.CreateInstance("Script"); Type type = o.GetType(); MethodInfo m = type.GetMethod("Main"); Object Result = m.Invoke(o, null); return(Result); } } catch (Exception e) { Console.WriteLine(e.ToString()); // Done with the temp assembly if (File.Exists(tempPath)) { File.Delete(tempPath); } } return(null); }
private Tuple <CompilerResults, string> Compile(TypeContext context) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } var sourceCode = GetCodeCompileUnit(context); var @params = new CompilerParameters { GenerateInMemory = false, GenerateExecutable = false, IncludeDebugInformation = Debug, TreatWarningsAsErrors = false, TempFiles = new TempFileCollection(GetTemporaryDirectory(), true), CompilerOptions = "/target:library /optimize /define:RAZORENGINE" }; var assemblies = GetAllReferences(context); var fileAssemblies = assemblies .Select(a => a.GetFile( msg => new ArgumentException( string.Format( "Unsupported CompilerReference given to CodeDom compiler (only references which can be resolved to files are supported: {0})!", msg)))) .Where(a => !string.IsNullOrWhiteSpace(a)) .Distinct(StringComparer.InvariantCultureIgnoreCase); @params.ReferencedAssemblies.AddRange(fileAssemblies.ToArray()); var tempDir = @params.TempFiles.TempDir; var assemblyName = Path.Combine(tempDir, String.Format("{0}.dll", GetAssemblyName(context))); @params.TempFiles.AddFile(assemblyName, true); @params.OutputAssembly = assemblyName; var results = _codeDomProvider.CompileAssemblyFromSource(@params, new [] { sourceCode }); if (Debug) { bool written = false; var targetFile = Path.Combine(results.TempFiles.TempDir, "generated_template." + SourceFileExtension); if (!written && !File.Exists(targetFile)) { File.WriteAllText(targetFile, sourceCode); written = true; } if (!written) { foreach (string item in results.TempFiles) { if (item.EndsWith("." + this.SourceFileExtension)) { File.Copy(item, targetFile, true); written = true; break; } } } } return(Tuple.Create(results, sourceCode)); }
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void GoodB2G2() { string data; if (IO.StaticReturnsTrue()) { data = ""; /* Initialize data */ /* read input from WebClient */ { try { using (WebClient client = new WebClient()) { using (StreamReader sr = new StreamReader(client.OpenRead("http://www.example.org/"))) { /* POTENTIAL FLAW: Read data from a web server with WebClient */ /* This will be reading the first "line" of the response body, * which could be very long if there are no newlines in the HTML */ data = sr.ReadLine(); } } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (IO.StaticReturnsTrue()) { int?parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } } }