internal bool MustTimeout(DateTime utcNow) { if (_timeoutState == 1) // fast check { if (TimeSpan.Compare(utcNow.Subtract(_timeoutStartTime), Timeout) >= 0) { // don't abort in debug mode try { if (CompilationConfiguration.IsDebuggingEnabled(this)) { return(false); } } catch { // ignore config errors return(false); } // abort the thread only if in cancelable state, avoiding race conditions // the caller MUST timeout if the return is true if (Interlocked.CompareExchange(ref _timeoutState, -1, 1) == 1) { return(true); } } } return(false); }
internal static CodeDomProvider CreateProvider(HttpContext context, string lang, out CompilerParameters par, out string tempdir) { CodeDomProvider ret = null; par = null; #if NET_2_0 CompilationSection config = (CompilationSection)WebConfigurationManager.GetWebApplicationSection("system.web/compilation"); Compiler comp = config.Compilers[lang]; if (comp == null) { CompilerInfo info = CodeDomProvider.GetCompilerInfo(lang); if (info != null && info.IsCodeDomProviderTypeValid) { ret = info.CreateProvider(); par = info.CreateDefaultCompilerParameters(); } } else { Type t = HttpApplication.LoadType(comp.Type, true); ret = Activator.CreateInstance(t) as CodeDomProvider; par = new CompilerParameters(); par.CompilerOptions = comp.CompilerOptions; par.WarningLevel = comp.WarningLevel; } #else CompilationConfiguration config; config = CompilationConfiguration.GetInstance(context); ret = config.GetProvider(lang); par = new CompilerParameters(); par.CompilerOptions = config.GetCompilerOptions(lang); par.WarningLevel = config.GetWarningLevel(lang); #endif tempdir = config.TempDirectory; return(ret); }
public LahdaLexer(CompilationConfiguration configuration) : base(configuration) { configuration.AddKeyword(KeywordType.Crash, "crash"); configuration.AddKeyword(KeywordType.If, "if"); configuration.AddKeyword(KeywordType.Else, "else"); configuration.AddKeyword(KeywordType.Break, "break"); configuration.AddKeyword(KeywordType.Continue, "continue"); configuration.AddKeyword(KeywordType.While, "while"); configuration.AddKeyword(KeywordType.Do, "do"); configuration.AddKeyword(KeywordType.For, "for"); configuration.AddKeyword(KeywordType.Float, "float"); configuration.AddKeyword(KeywordType.Forever, "forever"); configuration.AddKeyword(KeywordType.Reset, "reset"); configuration.AddKeyword(KeywordType.Var, "var"); configuration.AddKeyword(KeywordType.Until, "until"); configuration.AddKeyword(KeywordType.False, "false"); configuration.AddKeyword(KeywordType.True, "true"); configuration.AddKeyword(KeywordType.String, "string"); configuration.AddKeyword(KeywordType.Print, "print"); configuration.AddKeyword(KeywordType.Return, "say"); configuration.AddOperator(OperatorType.Reference, "@"); configuration.AddOperator(OperatorType.Dereference, ":"); configuration.AddOperator(OperatorType.Comma, ","); configuration.AddOperator(OperatorType.Increment, "++"); configuration.AddOperator(OperatorType.Decrement, "--"); configuration.AddOperator(OperatorType.Negate, "!"); configuration.AddOperator(OperatorType.Add, "+"); configuration.AddOperator(OperatorType.Sub, "-"); configuration.AddOperator(OperatorType.Mul, "*"); configuration.AddOperator(OperatorType.Pow, "^"); configuration.AddOperator(OperatorType.Div, "/"); configuration.AddOperator(OperatorType.EuclidianDiv, "//"); configuration.AddOperator(OperatorType.Mod, "%"); configuration.AddOperator(OperatorType.AddAssign, "+="); configuration.AddOperator(OperatorType.SubAssign, "-="); configuration.AddOperator(OperatorType.MulAssign, "*="); configuration.AddOperator(OperatorType.PowAssign, "^="); configuration.AddOperator(OperatorType.DivAssign, "/="); configuration.AddOperator(OperatorType.EuclidianDivAssign, "//="); configuration.AddOperator(OperatorType.ModAssign, "%="); configuration.AddOperator(OperatorType.Assign, "="); configuration.AddOperator(OperatorType.BitwiseAnd, "&"); configuration.AddOperator(OperatorType.AndAlso, "&&"); configuration.AddOperator(OperatorType.BitwiseOr, "|"); configuration.AddOperator(OperatorType.OrElse, "||"); configuration.AddOperator(OperatorType.BraceOpen, "{"); configuration.AddOperator(OperatorType.BraceClose, "}"); configuration.AddOperator(OperatorType.ParentheseOpen, "("); configuration.AddOperator(OperatorType.ParentheseClose, ")"); configuration.AddOperator(OperatorType.Equals, "=="); configuration.AddOperator(OperatorType.NotEquals, "!="); configuration.AddOperator(OperatorType.Greater, ">"); configuration.AddOperator(OperatorType.NotGreater, "<="); configuration.AddOperator(OperatorType.Less, "<"); configuration.AddOperator(OperatorType.NotLess, ">="); configuration.AddOperator(OperatorType.BracketOpen, "["); configuration.AddOperator(OperatorType.BracketClose, "]"); }
static void GetExtraAssemblies(CompilerParameters options) { StringCollection refAsm = options.ReferencedAssemblies; string asmLocation; #if NET_2_0 string asmName; ArrayList al = WebConfigurationManager.ExtraAssemblies; if (al != null && al.Count > 0) { foreach (object o in al) { asmName = o as string; if (asmName != null && !refAsm.Contains(asmName)) { refAsm.Add(asmName); } } } Assembly asm; IList list = BuildManager.CodeAssemblies; if (list != null && list.Count > 0) { foreach (object o in list) { asm = o as Assembly; if (asm == null) { continue; } asmName = asm.Location; if (asmName != null && !refAsm.Contains(asmName)) { refAsm.Add(asmName); } } } list = BuildManager.TopLevelAssemblies; if (list != null && list.Count > 0) { foreach (object o in list) { asm = o as Assembly; if (o == null) { continue; } asmName = asm.Location; if (!refAsm.Contains(asmName)) { refAsm.Add(asmName); } } } CompilationSection cfg = WebConfigurationManager.GetWebApplicationSection("system.web/compilation") as CompilationSection; AssemblyCollection asmcoll = cfg != null ? cfg.Assemblies : null; if (asmcoll == null) { return; } foreach (AssemblyInfo ai in asmcoll) { asmLocation = GetAssemblyLocationFromName(ai.Assembly); if (asmLocation == null || refAsm.Contains(asmLocation)) { continue; } refAsm.Add(asmLocation); } #else CompilationConfiguration cfg = CompilationConfiguration.GetInstance(HttpContext.Current); ArrayList asmcoll = cfg != null ? cfg.Assemblies : null; if (asmcoll == null) { return; } foreach (string asm in asmcoll) { asmLocation = GetAssemblyLocationFromName(asm); if (asmLocation == null || refAsm.Contains(asmLocation)) { continue; } refAsm.Add(asmLocation); } #endif }
private static void BatchCompile(ArrayList inputList, HttpContext context, string virtualDir) { Exception errorException = null; // Used to create temporary source files TempFileCollection tempFiles = new TempFileCollection(HttpRuntime.CodegenDirInternal); // Counter to name generated files uniquely int fileCount = 0; int maxBatchGeneratedFileSize = CompilationConfiguration.GetMaxBatchGeneratedFileSize(context); int maxBatchSize = CompilationConfiguration.GetMaxBatchSize(context); Hashtable languageBuckets = new Hashtable(); // Go through all the files that need to be compiled foreach (BatchCompilationEntry currentPage in inputList) { // precompile, and skip pages that fail to precompile try { currentPage.Precompile(); } catch (Exception e) { // remember the first exception if (errorException == null) { errorException = e; } Debug.Trace("Batching", "Skipping " + currentPage.PageFilename + " due to parse error (" + e.Message + ")"); continue; } // Skip trivial pages and pages that have the debug flag if (currentPage.IsTrivialPage() || currentPage.IsDebugPage()) { continue; } // Determine what language bucket it belongs to based on the CompilerInfo CompilerInfo compInfo = currentPage.CompilerInfo; PagesWithSameCompilerInfo pwsci = (PagesWithSameCompilerInfo)languageBuckets[compInfo]; if (pwsci == null) { pwsci = new PagesWithSameCompilerInfo(currentPage.CompilerInfo.CompilerType, maxBatchGeneratedFileSize * 1024, maxBatchSize); languageBuckets[compInfo] = pwsci; } ICodeGenerator generator = pwsci.CodeProvider.CreateGenerator(); // Build the CodeDOM tree for the page currentPage.BuildCodeModel(generator, pwsci._stringResourceBuilder); CodeCompileUnit compileUnit = currentPage.GetCodeModel(); // Generate a temporary source file from the CodeDOM tree string filename = tempFiles.AddExtension( (fileCount++) + "." + pwsci.CodeProvider.FileExtension, true /*keepFiles*/); Stream temp = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read); try { StreamWriter sw = new StreamWriter(temp, Encoding.UTF8); generator.GenerateCodeFromCompileUnit(compileUnit, sw, null /*CodeGeneratorOptions*/); sw.Flush(); sw.Close(); } finally { temp.Close(); } currentPage.GeneratedSourceFile = filename; // This releases a number of things that are no longer needed after this point currentPage.PostSourceCodeGeneration(); // Add it to the language bucket pwsci.AddPage(currentPage); // If the bucket is full, compile all its pages and get rid of it if (pwsci.IsBucketFull) { try { BasicBatchCompilation(context, compInfo.Clone(), pwsci); // Tell the server that we're still running to make sure it doesn't kill us (ASURT 96452) context.SendEmptyResponse(); } catch (Exception e) { // remember the first exception if (errorException == null) { errorException = e; } } languageBuckets.Remove(compInfo); } } // Compile whatever is left in all the buckets for (IDictionaryEnumerator de = (IDictionaryEnumerator)languageBuckets.GetEnumerator(); de.MoveNext();) { try { BasicBatchCompilation(context, ((CompilerInfo)de.Key).Clone(), (PagesWithSameCompilerInfo)de.Value); } catch (Exception e) { // remember the first exception if (errorException == null) { errorException = e; } } } // If there was an error, rethrow it if (errorException != null) { throw new HttpException(null, errorException); } }
/* * Perform initialization work that should only be done once (per app domain). */ private static void DoFirstTimeInit(HttpContext context) { // Find out how many recompilations we allow before restarting the appdomain s_maxRecompilations = CompilationConfiguration.GetRecompilationsBeforeAppRestarts(context); // Create the temp files directory if it's not already there string tempFilePath = HttpRuntime.CodegenDirInternal; if (!FileUtil.DirectoryExists(tempFilePath)) { try { Directory.CreateDirectory(tempFilePath); } catch (IOException e) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Failed_to_create_temp_dir, HttpRuntime.GetSafePath(tempFilePath)), e); } } long specialFilesCombinedHash = ReadPreservedSpecialFilesCombinedHash(); Debug.Trace("PreservedAssemblyEntry", "specialFilesCombinedHash=" + specialFilesCombinedHash); // Delete all the non essential files left over in the codegen dir, unless // specialFilesCombinedHash is 0, in which case we delete *everything* further down if (specialFilesCombinedHash != 0) { RemoveOldTempFiles(); } // Use a DateTimeCombiner object to handle the time stamps of all the 'special' // files that all compilations depend on: // - The config files (excluding the ones from subdirectories) // - global.asax // - System.Web.dll (in case there is a newer version of ASP.NET) DateTimeCombiner specialFilesDateTimeCombiner = new DateTimeCombiner(); // Add a check for the app's physical path, in case it changes (ASURT 12975) specialFilesDateTimeCombiner.AddObject(context.Request.PhysicalApplicationPath); // Process the config files. Note that this only includes the top level ones, // namely the machine one, and the one in the root of the app. The others are // handled as regular dependencies. string appPath = context.Request.ApplicationPath; string[] configFiles = context.GetConfigurationDependencies(appPath); _numTopLevelConfigFiles = configFiles.Length; for (int i = 0; i < _numTopLevelConfigFiles; i++) { specialFilesDateTimeCombiner.AddFile(configFiles[i]); } // Process global.asax string appFileName = HttpApplicationFactory.GetApplicationFile(context); specialFilesDateTimeCombiner.AddFile(appFileName); // Process System.Web.dll string aspBinaryFileName = typeof(HttpRuntime).Module.FullyQualifiedName; specialFilesDateTimeCombiner.AddFile(aspBinaryFileName); // If they don't match, cleanup everything and write the new hash file if (specialFilesDateTimeCombiner.CombinedHash != specialFilesCombinedHash) { Debug.Trace("PreservedAssemblyEntry", "EnsureFirstTimeInit: hash codes don't match. Old=" + specialFilesCombinedHash + " New=" + specialFilesDateTimeCombiner.CombinedHash); RemoveAllCodeGenFiles(); WritePreservedSpecialFilesCombinedHash(specialFilesDateTimeCombiner.CombinedHash); } else { Debug.Trace("PreservedAssemblyEntry", "PreservedAssemblyEntry: the special files are up to date"); } }
/* * Try batching the directory if not done yet. */ private static bool BatchCompileDirectory(HttpContext context, string baseVirtualDir) { // Don't do it if batching is disabled if (!CompilationConfiguration.IsBatchingEnabled(context)) { return(false); } if (AlreadyBatched(baseVirtualDir)) { return(false); } Debug.Trace("PreservedAssemblyEntry", "Need to batch compile " + baseVirtualDir); // If we're already in a batch compilation tread, no need to start another one if (BackgroundBatchCompiler.IsBatchCompilationThread()) { Debug.Trace("PreservedAssemblyEntry", "Already in batch compilation thread. No need to start a new one."); CodeDomBatchManager.BatchCompile(baseVirtualDir, context); return(true); } // Notify HttpRuntime so that it might need to abort compilation on shutdown HttpRuntime.NotifyThatSomeBatchCompilationStarted(); ManualResetEvent batchEvent = new ManualResetEvent(false); // Pass it a Clone of the context, since it's not thread safe. Mostly, this is important // for the ConfigPath (ASURT 82744) BackgroundBatchCompiler bbc = new BackgroundBatchCompiler(context.Clone(), baseVirtualDir, batchEvent); // Start the batch processing try { ThreadPool.QueueUserWorkItem(bbc.BatchCallback); } catch { return(false); } // Register for BeforeDoneWithSession event context.BeforeDoneWithSession += new EventHandler(bbc.BeforeDoneWithSessionHandler); // Wait a certain time for it to complete int timeout = 1000 * CompilationConfiguration.GetBatchTimeout(context); Debug.Trace("PreservedAssemblyEntry", "Waiting for " + timeout + " ms"); if (batchEvent.WaitOne(timeout, false)) { Debug.Trace("PreservedAssemblyEntry", "The background thread is done for " + baseVirtualDir + " (Success=" + bbc.Success + ")"); return(bbc.Success); } // It didn't have time to complete. Let it run in the background. Debug.Trace("PreservedAssemblyEntry", "The background thread is still going for " + baseVirtualDir); // Add it to the list of background compilations, in case it needs to be aborted AddBackgroundBatchCompilation(bbc); bbc.WasAddedToBackgroundThreadsList = true; return(false); }
private SourceCompilerCachedEntry CompileAndCache() { BaseCompiler.GenerateCompilerParameters(_compilParams); // Get the set of config assemblies for our context IDictionary configAssemblies = CompilationConfiguration.GetAssembliesFromContext(_context); if (_assemblies == null) { _assemblies = new Hashtable(); } // Add all the assemblies from the config object to the hashtable // This guarantees uniqueness if (configAssemblies != null) { foreach (Assembly asm in configAssemblies.Values) { _assemblies[asm] = null; } } // And the assembly of the application object (global.asax) _assemblies[HttpApplicationFactory.ApplicationType.Assembly] = null; // Now add all the passed in assemblies to the compilParams foreach (Assembly asm in _assemblies.Keys) { _compilParams.ReferencedAssemblies.Add(Util.GetAssemblyCodeBase(asm)); } // Instantiate the Compiler CodeDomProvider codeProvider = (CodeDomProvider)HttpRuntime.CreatePublicInstance(_compilerType); ICodeCompiler compiler = codeProvider.CreateCompiler(); CompilerResults results; // Compile the source file or string into an assembly try { _utcStart = DateTime.UtcNow; // If we have a source file, read it as a string and compile it. This way, // the compiler never needs to read the original file, avoiding permission // issues (see ASURT 112718) if (_sourceString == null) { _sourceString = Util.StringFromFile(_physicalPath, _context); // Put in some context so that the file can be debugged. _linePragma = new CodeLinePragma(_physicalPath, 1); } CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(_sourceString); snippetCompileUnit.LinePragma = _linePragma; results = compiler.CompileAssemblyFromDom(_compilParams, snippetCompileUnit); } catch (Exception e) { throw new HttpUnhandledException(HttpRuntime.FormatResourceString(SR.CompilationUnhandledException, codeProvider.GetType().FullName), e); } BaseCompiler.ThrowIfCompilerErrors(results, codeProvider, null, _physicalPath, _sourceString); SourceCompilerCachedEntry scce = new SourceCompilerCachedEntry(); // Load the assembly scce._assembly = results.CompiledAssembly; // If we have a type name, load the type from the assembly if (_typeName != null) { scce._type = scce._assembly.GetType(_typeName); // If the type could not be loaded, delete the assembly and rethrow if (scce._type == null) { PreservedAssemblyEntry.RemoveOutOfDateAssembly(scce._assembly.GetName().Name); // Remember why we failed _typeNotFoundInAssembly = true; throw new HttpException( HttpRuntime.FormatResourceString(SR.Could_not_create_type, _typeName)); } } CacheEntryToDisk(scce); CacheEntryToMemory(scce); return(scce); }
public AbstractLexer(CompilationConfiguration configuration) { Configuration = configuration; }