public void ShouldFindMethodByIdentifier() { var searcher = new CciMethodMatcher(_context); var methods = _module.GetAllTypes().SelectMany(t => t.Methods).ToList(); IMethodDefinition method = methods.SingleOrDefault(searcher.Matches); Assert.IsNotNull(method); }
public void ShouldFindMethodByIdentifier() { var searcher = new CciMethodMatcher(_context); var methods = _module.GetAllTypes().SelectMany(t => t.Methods).ToList(); var methodsMatch = methods.Where(searcher.Matches).ToList(); Assert.IsNotNull(methodsMatch.Single()); }
static void Main(string[] args) { PdbReader pdbReader = new PdbReader(@"D:\Honzik\Desktop\Mandelbrot\Mandelbrot\bin\Debug\Mandelbrot.exe"); IModule module = pdbReader.Module; foreach (var namedTypeDefinition in module.GetAllTypes()) { PropertyInfo propertyInfo2 = namedTypeDefinition.GetType().GetProperty("TokenValue", BindingFlags.NonPublic | BindingFlags.Instance); uint value2 = (uint)propertyInfo2.GetValue(namedTypeDefinition, null); foreach (var methodDefinition in namedTypeDefinition.Methods) { Console.WriteLine(methodDefinition.Name); PropertyInfo propertyInfo = methodDefinition.GetType().GetProperty("TokenValue", BindingFlags.NonPublic | BindingFlags.Instance); uint value = (uint)propertyInfo.GetValue(methodDefinition, null); foreach (var location in methodDefinition.Locations) { foreach (var primarySourceLocation in pdbReader.GetAllPrimarySourceLocationsFor(location)) { if (primarySourceLocation != null) { Console.WriteLine("line {0}, {1}:{2}", primarySourceLocation.StartLine, primarySourceLocation.StartColumn, primarySourceLocation.EndColumn); } } } } } }
public override void Initialize() { CoreAssembly = Host.LoadAssembly(Host.CoreAssemblySymbolicIdentity); var host = new PeReader.DefaultHost(); IModule module = OperatorUtils.CompileModuleFromCode( @"using System; namespace VisualMutatorGeneratedNamespace { public class VisualMutatorGeneratedClass { public static int FailOnZero(int x) { if(x == 0) throw new InvalidOperationException(""FailOnZero: x""); return x; } } }", host); GeneratedType = (NamespaceTypeDefinition)module.GetAllTypes().Single(t => t.Name.Value == "VisualMutatorGeneratedClass"); var methodBody = TypeHelper.GetMethod(GeneratedType, host.NameTable.GetNameFor("FailOnZero"), host.PlatformType.SystemInt32).Body; var generatedBody = (SourceMethodBody)methodBody; GeneratedBlock = generatedBody.Block; host.Dispose(); }
private void PopulateSourceLocations() { IModule module = PdbReader.Module; foreach (INamedTypeDefinition namedTypeDefinition in module.GetAllTypes()) { foreach (IMethodDefinition methodDefinition in namedTypeDefinition.Methods) { PropertyInfo propertyInfo = methodDefinition.GetType().GetProperty("TokenValue", BindingFlags.NonPublic | BindingFlags.Instance); var methodMdToken = (uint)propertyInfo.GetValue(methodDefinition, null); var primarySourceLocations = new List <IPrimarySourceLocation>(); foreach (ILocation location in methodDefinition.Locations) { IEnumerable <IPrimarySourceLocation> notNullLocations = PdbReader.GetAllPrimarySourceLocationsFor(location).Where(sl => sl != null); primarySourceLocations.AddRange(notNullLocations); } IEnumerable <CciMethodLine> cciMethodLines = primarySourceLocations.Where(sl => sl.StartLine < MaxSourceLineLength).Select(sl => new CciMethodLine(sl)); LocationsByToken[methodMdToken] = cciMethodLines; } } }
protected IReadOnlyCollection <INamedTypeDefinition> GetAnalyzableTypes(IModule module) { var types = from t in module.GetAllTypes() where (t.IsClass || t.IsStruct) && !t.IsStatic && !t.IsEnum && !t.IsInterface select t; return(new List <INamedTypeDefinition>(types)); }
public static void SetupStubs(IModule stubsModule) { NameToTypeDefMap = new Dictionary <string, ITypeDefinition>(); NameToNameMap = new Dictionary <string, string>(); NameToNameMap.Add("System.Threading.Tasks.VoidTaskResult", "Daffodil.Stubs.VoidTaskResult"); NameToNameMap.Add("System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "Daffodil.Stubs.AsyncTaskMethodBuilder"); NameToNameMap.Add("System.Runtime.CompilerServices.AsyncTaskMethodBuilder<TResult>", "Daffodil.Stubs.AsyncTaskMethodBuilder<TResult>"); NameToNameMap.Add("System.Threading.Tasks.Task", "Daffodil.Stubs.Task"); NameToNameMap.Add("System.Threading.Tasks.Task<TResult>", "Daffodil.Stubs.Task<TResult>"); NameToNameMap.Add("System.Runtime.CompilerServices.TaskAwaiter", "Daffodil.Stubs.TaskAwaiter"); NameToNameMap.Add("System.Runtime.CompilerServices.TaskAwaiter<TResult>", "Daffodil.Stubs.TaskAwaiter<TResult>"); NameToNameMap.Add("System.Runtime.CompilerServices.IAsyncStateMachine", "Daffodil.Stubs.IAsyncStateMachine"); foreach (ITypeDefinition ty in stubsModule.GetAllTypes().OfType <INamedTypeDefinition>().ToList()) { NameToTypeDefMap.Add(ty.FullName(), ty); } }
static public TreeNode BuildModuleNodes(IModule module, WorkspaceUnit unit) { var node = new TreeNode(); CreateTreeNodes(new ModuleNodeTag <TreeNode>(node, module, unit)); // Add namespace nodes. var types = module.GetAllTypes(); var topTypes = new List <INamedTypeDefinition>(); foreach (var t in types) { if (t is INamespaceTypeDefinition) { topTypes.Add(t); } } var namespaceTypes = new Dictionary <string, List <INamedTypeDefinition> >(); foreach (var t in topTypes) { var ns = TypeHelper.GetNamespaceName( (t as INamespaceTypeDefinition).ContainingUnitNamespace, NameFormattingOptions.None); if (!namespaceTypes.ContainsKey(ns)) { namespaceTypes.Add(ns, new List <INamedTypeDefinition>()); } namespaceTypes[ns].Add(t); } foreach (var ns in namespaceTypes.Keys) { node.Nodes.Add(BuildNamespaceNodes(ns, namespaceTypes[ns])); } return(node); }
static void Initialize(ISet <ITypeDefinition> classesSet, ISet <ITypeDefinition> entryPtList, IModule rootModule, bool rootIsExe) { foreach (ITypeDefinition ty in rootModule.GetAllTypes()) { if (ty is INamedTypeDefinition && !ty.IsGeneric && !ty.IsAbstract && ty.FullName() != "<Module>") { if (rootIsExe) { if (Utils.GetMethodByName(ty, "Main") != null) { classesSet.Add(ty); entryPtList.Add(ty); } } else { classesSet.Add(ty); entryPtList.Add(ty); } } } }
static void Main(string[] args) { if (args == null || args.Length == 0) { Console.WriteLine("usage: peToText [path]fileName.ext"); return; } PdbReader pdbReader = new PdbReader(args[0]); IModule module = pdbReader.Module; foreach (var namedTypeDefinition in module.GetAllTypes()) { PropertyInfo propertyInfo2 = namedTypeDefinition.GetType().GetProperty("TokenValue", BindingFlags.NonPublic | BindingFlags.Instance); uint value2 = (uint)propertyInfo2.GetValue(namedTypeDefinition, null); foreach (var methodDefinition in namedTypeDefinition.Methods) { Console.WriteLine(methodDefinition.Name); PropertyInfo propertyInfo = methodDefinition.GetType().GetProperty("TokenValue", BindingFlags.NonPublic | BindingFlags.Instance); uint value = (uint)propertyInfo.GetValue(methodDefinition, null); foreach (var location in methodDefinition.Locations) { foreach (var primarySourceLocation in pdbReader.GetAllPrimarySourceLocationsFor(location)) { if (primarySourceLocation != null) { Console.WriteLine("line {0}, {1}:{2}", primarySourceLocation.StartLine, primarySourceLocation.StartColumn, primarySourceLocation.EndColumn); } } } } } }
private void LoadSavedModules(IMetadataHost host, string modulesFN, IDictionary <string, IModule> moduleNameToModuleMap) { using (StreamReader sr = new StreamReader(modulesFN)) { string line; while ((line = sr.ReadLine()) != null) { line = line.Trim(); if (!string.IsNullOrEmpty(line)) { int ndx = line.IndexOf(" LOCATION:"); string fileName = line.Substring(ndx + 10); string moduleName = line.Substring(0, ndx).Split(':')[1]; IModule module = host.LoadUnitFrom(fileName) as IModule; moduleNameToModuleMap[moduleName] = module; List <INamedTypeDefinition> l = module.GetAllTypes().OfType <INamedTypeDefinition>().ToList(); if (module == null || module == Dummy.Module || module == Dummy.Assembly) { throw new Exception("The input is not a valid CLR module or assembly."); } } } } }
/// <summary> /// Performs some computation with the given module. /// </summary> public void Visit(IModule module) { if (module.ModuleName.Value.IndexOfAny(badPosixNameChars) > 0) this.ReportError(MetadataError.NotPosixAssemblyName, module, module.ModuleName.Value); foreach (var type in module.GetAllTypes()) { if (this.allTypes.Contains(type)) { this.ReportError(MetadataError.DuplicateEntryInAllTypes, module); continue; } this.allTypes.Add(type); } this.Visit((IUnit)module); //check for duplicate assembly references var refsSeenSoFar = new Dictionary<AssemblyIdentity, IAssemblyReference>(); foreach (var assemblyReference in module.AssemblyReferences) { IAssemblyReference duplicate = null; if (refsSeenSoFar.TryGetValue(assemblyReference.AssemblyIdentity, out duplicate)) this.ReportError(MetadataError.DuplicateAssemblyReference, assemblyReference, duplicate); else refsSeenSoFar.Add(assemblyReference.AssemblyIdentity, assemblyReference); } foreach (var typeMemberReference in module.GetTypeMemberReferences()) this.Visit(typeMemberReference); foreach (var typeReference in module.GetTypeReferences()) this.Visit(typeReference); }
public static string Serialize(IModule module) { var types = module.GetAllTypes(); return(Serialize(types)); }
public void Compile(string fileName) { string appName = Path.GetFileNameWithoutExtension(fileName); string exeName = appName + ".exe"; string src = ""; using (TextReader file = new StreamReader(fileName)) { src = file.ReadToEnd(); } var nameTable = new NameTable(); using (var host = new PeReader.DefaultHost(nameTable)) { // Load Mirage types IModule module = host.LoadUnitFrom("Mirage.dll") as IModule; if (module == null || module is Dummy) { return; } var machineType = module.GetAllTypes().First(x => x.Name.Value == "Machine"); var inputType = module.GetAllTypes().First(x => x.Name.Value == "ConsoleInput"); var outputType = module.GetAllTypes().First(x => x.Name.Value == "ConsoleOutput"); // Create assembly var coreAssembly = host.LoadAssembly(host.CoreAssemblySymbolicIdentity); var assembly = new Assembly() { Name = nameTable.GetNameFor(appName), ModuleName = nameTable.GetNameFor(exeName), PlatformType = host.PlatformType, Kind = ModuleKind.ConsoleApplication, RequiresStartupStub = host.PointerSize == 4, TargetRuntimeVersion = coreAssembly.TargetRuntimeVersion, }; assembly.AssemblyReferences.Add(coreAssembly); // Create namespace var rootUnitNamespace = new RootUnitNamespace(); assembly.UnitNamespaceRoot = rootUnitNamespace; rootUnitNamespace.Unit = assembly; // Create module class var moduleClass = new NamespaceTypeDefinition() { ContainingUnitNamespace = rootUnitNamespace, InternFactory = host.InternFactory, IsClass = true, Name = nameTable.GetNameFor("<Module>"), }; assembly.AllTypes.Add(moduleClass); // Create program class var programClass = new NamespaceTypeDefinition() { ContainingUnitNamespace = rootUnitNamespace, InternFactory = host.InternFactory, IsClass = true, IsPublic = true, Methods = new List <IMethodDefinition>(1), Name = nameTable.GetNameFor("Program"), }; programClass.BaseClasses = new List <ITypeReference>() { host.PlatformType.SystemObject }; rootUnitNamespace.Members.Add(programClass); // Add types to the assembly assembly.AllTypes.Add(machineType); foreach (var t in machineType.NestedTypes) { assembly.AllTypes.Add(t); } assembly.AllTypes.Add(inputType); assembly.AllTypes.Add(outputType); assembly.AllTypes.Add(programClass); // Create main method var mainMethod = new MethodDefinition() { ContainingTypeDefinition = programClass, InternFactory = host.InternFactory, IsCil = true, IsStatic = true, Name = nameTable.GetNameFor("Main"), Type = host.PlatformType.SystemVoid, Visibility = TypeMemberVisibility.Public, }; assembly.EntryPoint = mainMethod; programClass.Methods.Add(mainMethod); // Create constructors and methods IMethodReference machineConstructor = new Microsoft.Cci.MethodReference( host, machineType, CallingConvention.HasThis, host.PlatformType.SystemVoid, host.NameTable.Ctor, 0 ); IMethodReference inputConstructor = new Microsoft.Cci.MethodReference( host, inputType, CallingConvention.HasThis, host.PlatformType.SystemVoid, host.NameTable.Ctor, 0 ); var inputCast = TypeHelper.GetMethod(inputType, nameTable.GetNameFor("op_Implicit"), inputType); IMethodReference outputConstructor = new Microsoft.Cci.MethodReference( host, outputType, CallingConvention.HasThis, host.PlatformType.SystemVoid, host.NameTable.Ctor, 0 ); var outputCast = TypeHelper.GetMethod(outputType, nameTable.GetNameFor("op_Implicit"), outputType); var opIncPointers = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("IncPointers")); var opDecPointers = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("DecPointers")); var opIncHiPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("IncHiPointer")); var opDecHiPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("DecHiPointer")); var opReflectHiPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("ReflectHiPointer")); var opLoadHiPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("LoadHiPointer")); var opDragLoPointer = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("DragLoPointer")); var opXchPointers = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("XchPointers")); var opClear = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Clear")); var opAdd = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Add")); var opDec = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Dec")); var opNot = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Not")); var opAnd = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("And")); var opOr = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Or")); var opXor = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Xor")); var opSal = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Sal")); var opSar = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Sar")); var opLoadData = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("LoadData"), host.PlatformType.SystemString); var opInput = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Input"), inputCast.Type); var opOutput = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Output"), outputCast.Type); var opJz = TypeHelper.GetMethod(machineType, nameTable.GetNameFor("Jz")); // Create program code var labels = new Stack <ILGeneratorLabel>(100); var ilGenerator = new ILGenerator(host, mainMethod); ilGenerator.Emit(OperationCode.Newobj, machineConstructor); ilGenerator.Emit(OperationCode.Stloc_0); ilGenerator.Emit(OperationCode.Newobj, inputConstructor); ilGenerator.Emit(OperationCode.Stloc_1); ilGenerator.Emit(OperationCode.Newobj, outputConstructor); ilGenerator.Emit(OperationCode.Stloc_2); int pc = 0; while (pc < src.Length) { char opcode = src[pc++]; switch (opcode) { case '>': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opIncPointers); break; case '<': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opDecPointers); break; case ']': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opIncHiPointer); break; case '[': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opDecHiPointer); break; case '#': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opReflectHiPointer); break; case '$': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opLoadHiPointer); break; case '=': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opDragLoPointer); break; case '%': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opXchPointers); break; case '_': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opClear); break; case '+': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opAdd); break; case '-': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opDec); break; case '~': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opNot); break; case '&': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opAnd); break; case '|': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opOr); break; case '^': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opXor); break; case '*': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opSal); break; case '/': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opSar); break; case '(': int dataStart = pc; int dataEnd = dataStart; while (src[pc++] != ')') { dataEnd = pc; } ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Ldstr, src.Substring(dataStart, dataEnd - dataStart)); ilGenerator.Emit(OperationCode.Callvirt, opLoadData); break; case '?': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Ldloc_1); ilGenerator.Emit(OperationCode.Call, inputCast); ilGenerator.Emit(OperationCode.Callvirt, opInput); break; case '!': ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Ldloc_2); ilGenerator.Emit(OperationCode.Call, outputCast); ilGenerator.Emit(OperationCode.Callvirt, opOutput); break; case '{': var cycleStart = new ILGeneratorLabel(); var cycleEnd = new ILGeneratorLabel(); labels.Push(cycleStart); labels.Push(cycleEnd); ilGenerator.Emit(OperationCode.Br, cycleEnd); ilGenerator.MarkLabel(cycleStart); break; case '}': ilGenerator.MarkLabel(labels.Pop()); ilGenerator.Emit(OperationCode.Ldloc_0); ilGenerator.Emit(OperationCode.Callvirt, opJz); ilGenerator.Emit(OperationCode.Ldc_I4_0); ilGenerator.Emit(OperationCode.Ceq); ilGenerator.Emit(OperationCode.Stloc_3); ilGenerator.Emit(OperationCode.Ldloc_3); ilGenerator.Emit(OperationCode.Brtrue, labels.Pop()); break; default: break; } } ilGenerator.Emit(OperationCode.Ret); mainMethod.Body = new ILGeneratorMethodBody( ilGenerator, true, 8, mainMethod, new List <ILocalDefinition>() { new LocalDefinition() { Type = machineType }, new LocalDefinition() { Type = inputType }, new LocalDefinition() { Type = outputType }, new LocalDefinition() { Type = host.PlatformType.SystemInt32 }, }, Enumerable <ITypeDefinition> .Empty ); using (var peStream = File.Create(exeName)) { PeWriter.WritePeToStream(assembly, host, peStream); } } }
private void FindAllClosedStructuralReferencesIn(IModule module, Hashtable<ITypeReference> closedStructuralTypeReferences, Hashtable<IGenericMethodInstanceReference> closedGenericMethodInstances, bool followBaseClassReferencesIntoOtherModules) { Contract.Requires(module != null); Contract.Requires(closedStructuralTypeReferences != null); Contract.Requires(closedGenericMethodInstances != null); var finder = new StructuralReferenceFinder(closedStructuralTypeReferences, closedGenericMethodInstances, followBaseClassReferencesIntoOtherModules); foreach (var type in module.GetAllTypes()) { Contract.Assume(type != null); if (type is INestedTypeDefinition) continue; //These are traversed via their containers finder.Traverse(type); } }
public static MemoryStream RewriteProgramIL(CeleriacArgs celeriacArgs, TypeManager typeManager) { if (String.IsNullOrWhiteSpace(celeriacArgs.AssemblyPath)) { throw new FileNotFoundException("Path to program to be profiled not provided"); } Stream resultStream; var host = typeManager.Host; IModule /*?*/ module = host.LoadUnitFrom(celeriacArgs.AssemblyPath) as IModule; if (module == null || module == Dummy.Module || module == Dummy.Assembly) { throw new FileNotFoundException("Given path is not a PE file containing a CLR" + " assembly, or an error occurred when loading it.", celeriacArgs.AssemblyPath); } if (module.GetAllTypes().Any( type => type.Name.ToString().Equals(ILRewriter.ArgumentStoringClassName))) { throw new InvalidOperationException("Program has already been instrumented."); } string pdbFile = Path.ChangeExtension(module.Location, "pdb"); Assembly mutable = null; using (var pdbReader = LoadPdbReaderAndFile(celeriacArgs, typeManager, module, pdbFile)) { AssemblySummary comparabilityManager = GenerateComparability(celeriacArgs, typeManager, host, module, pdbReader, ref mutable); if (celeriacArgs.GenerateComparability && celeriacArgs.ComparabilityFile == null) { return(null); } ILRewriter mutator = new ILRewriter(host, pdbReader, celeriacArgs, typeManager, comparabilityManager); module = mutator.Visit(mutable, Path.Combine(FindVisitorDir(), VisitorDll)); if (celeriacArgs.EmitNullaryInfo || celeriacArgs.GenerateComparability) { return(null); } // Remove the old PDB file try { File.Delete(pdbFile); } catch (UnauthorizedAccessException) { // If they are running the debugger we might not be able to delete the file // Save the pdb elsewhere in this case. pdbFile = module.Location + ".pdb"; } if (celeriacArgs.SaveProgram != null) { resultStream = new FileStream(celeriacArgs.SaveProgram, FileMode.Create); } else { resultStream = new MemoryStream(); } #if __MonoCS__ // Reading / Writing DEBUG information on Mono is not supported by CCI PdbWriter pdbWriter = null; #else var pdbWriter = new PdbWriter(pdbFile, pdbReader); #endif // Need to not pass in a local scope provider until such time as we have one // that will use the mutator to remap things (like the type of a scope // constant) from the original assembly to the mutated one. using (pdbWriter) { PeWriter.WritePeToStream(module, host, resultStream, pdbReader, null, pdbWriter); } } if (celeriacArgs.SaveProgram != null) { // We aren't going to run the program, so no need to return anything, // but close the file stream. resultStream.Close(); return(null); } else { return((MemoryStream)resultStream); // success } }