Exemple #1
0
        /// <summary>
        /// Processes the specified type's fields to fill in required data.
        /// </summary>
        /// <param name="TheLibrary">The library from which the type originated.</param>
        /// <param name="theTypeInfo">The type info to process.</param>
        public static void ProcessTypeFields(IL.ILLibrary TheLibrary, TypeInfo theTypeInfo)
        {
            if (theTypeInfo.ProcessedFields)
            {
                return;
            }

            theTypeInfo.ProcessedFields = true;

            int totalOffset = 0;

            //Base class fields
            if (theTypeInfo.UnderlyingType.BaseType != null)
            {
                Type baseType = theTypeInfo.UnderlyingType.BaseType;
                if (!baseType.AssemblyQualifiedName.Contains("mscorlib"))
                {
                    totalOffset = TheLibrary.GetTypeInfo(baseType).SizeOnHeapInBytes;
                }
            }

            foreach (FieldInfo aFieldInfo in theTypeInfo.FieldInfos)
            {
                if (!aFieldInfo.IsStatic)
                {
                    aFieldInfo.OffsetInBytes = totalOffset;
                    TypeInfo fieldTypeInfo = TheLibrary.GetTypeInfo(aFieldInfo.FieldType);
                    totalOffset += fieldTypeInfo.IsValueType ? fieldTypeInfo.SizeOnHeapInBytes : fieldTypeInfo.SizeOnStackInBytes;
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Processes the specified type info to fill in the required data.
        /// </summary>
        /// <param name="TheLibrary">The library from which the type originated.</param>
        /// <param name="theTypeInfo">The type info to process.</param>
        public static void ProcessType(IL.ILLibrary TheLibrary, TypeInfo theTypeInfo)
        {
            if (theTypeInfo.Processed)
            {
                return;
            }

            theTypeInfo.Processed = true;

            theTypeInfo.IsGCManaged = GetIsGCManaged(theTypeInfo.UnderlyingType);

            if (theTypeInfo.IsValueType || theTypeInfo.IsPointer)
            {
                theTypeInfo.SizeOnStackInBytes = GetSizeOnStackInBytes(theTypeInfo.UnderlyingType);
                theTypeInfo.SizeOnHeapInBytes  = GetSizeOnHeapInBytes(theTypeInfo.UnderlyingType);
            }
            else
            {
                theTypeInfo.SizeOnStackInBytes = GetSizeOnStackInBytes(theTypeInfo.UnderlyingType);

                theTypeInfo.SizeOnHeapInBytes = 0;
                if (theTypeInfo.UnderlyingType.BaseType != null)
                {
                    Type baseType = theTypeInfo.UnderlyingType.BaseType;
                    if (!baseType.AssemblyQualifiedName.Contains("mscorlib"))
                    {
                        TypeInfo baseTypeInfo = TheLibrary.GetTypeInfo(baseType, false);
                        ProcessType(TheLibrary, baseTypeInfo);
                        theTypeInfo.SizeOnHeapInBytes += baseTypeInfo.SizeOnHeapInBytes;
                    }
                }
                foreach (FieldInfo aFieldInfo in theTypeInfo.FieldInfos)
                {
                    if (!aFieldInfo.IsStatic)
                    {
                        TypeInfo fieldTypeInfo = TheLibrary.GetTypeInfo(aFieldInfo.FieldType, false);
                        if (fieldTypeInfo.IsValueType || fieldTypeInfo.IsPointer)
                        {
                            ProcessType(TheLibrary, fieldTypeInfo);
                        }
                        theTypeInfo.SizeOnHeapInBytes += fieldTypeInfo.IsValueType ? fieldTypeInfo.SizeOnHeapInBytes : Options.AddressSizeInBytes;
                    }
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Compiles the specified IL Library and any dependencies using the ASM Preprocesor and ASM Processor.
        /// </summary>
        /// <remarks>
        /// The ASM Compiler's steps convert the ASM into machine code.
        /// </remarks>
        /// <param name="TheILLibrary">The library to compile.</param>
        /// <returns>CompileResult.OK if all steps complete successfully.</returns>
        public static CompileResult Compile(IL.ILLibrary TheILLibrary)
        {
            CompileResult Result = CompileResult.OK;

            foreach (IL.ILLibrary depLib in TheILLibrary.Dependencies)
            {
                Result = Result == CompileResult.OK ? Compile(depLib) : Result;
            }

            Result = Result == CompileResult.OK ? ExecuteASMPreprocessor(TheILLibrary.TheASMLibrary) : Result;

            if (Result == CompileResult.OK)
            {
                Result = ExecuteASMProcessor(TheILLibrary.TheASMLibrary);
            }

            return(Result);
        }
Exemple #4
0
        /// <summary>
        /// Scans the library for types.
        /// </summary>
        /// <param name="TheLibrary">The library to scan.</param>
        public static void ScanTypes(IL.ILLibrary TheLibrary)
        {
            if (TheLibrary == null)
            {
                return;
            }
            else if (TheLibrary.TypeInfos.Count != 0)
            {
                //Already scanned
                return;
            }

            foreach (IL.ILLibrary aDependency in TheLibrary.Dependencies)
            {
                ScanTypes(aDependency);
            }

            List <Type> types = TheLibrary.TheAssembly.GetTypes().ToList();

            //Add in the standard types (which come from mscorlib)
            //#region Standard Types (from mscorlib)

            //types.Add(typeof(object));

            //types.Add(typeof(float));
            //types.Add(typeof(double));
            //types.Add(typeof(decimal));
            //types.Add(typeof(string));
            //types.Add(typeof(IntPtr));

            //types.Add(typeof(void));
            //types.Add(typeof(bool));
            //types.Add(typeof(byte));
            //types.Add(typeof(sbyte));
            //types.Add(typeof(char));
            //types.Add(typeof(int));
            //types.Add(typeof(long));
            //types.Add(typeof(Int16));
            //types.Add(typeof(Int32));
            //types.Add(typeof(Int64));
            //types.Add(typeof(UInt16));
            //types.Add(typeof(UInt32));
            //types.Add(typeof(UInt64));

            //types.Add(typeof(void*));
            //types.Add(typeof(bool*));
            //types.Add(typeof(byte*));
            //types.Add(typeof(sbyte*));
            //types.Add(typeof(char*));
            //types.Add(typeof(int*));
            //types.Add(typeof(long*));
            //types.Add(typeof(Int16*));
            //types.Add(typeof(Int32*));
            //types.Add(typeof(Int64*));
            //types.Add(typeof(UInt16*));
            //types.Add(typeof(UInt32*));
            //types.Add(typeof(UInt64*));

            //#endregion

            foreach (Type aType in types)
            {
                ScanType(TheLibrary, aType);
            }

            for (int i = 0; i < TheLibrary.TypeInfos.Count; i++)
            {
                ProcessType(TheLibrary, TheLibrary.TypeInfos[i]);
            }

            for (int i = 0; i < TheLibrary.TypeInfos.Count; i++)
            {
                ProcessTypeFields(TheLibrary, TheLibrary.TypeInfos[i]);
            }
        }
Exemple #5
0
        /// <summary>
        /// Scans a type to generate type info for the type. Also scans methods and constructors of the type
        /// amongst some other information.
        /// </summary>
        /// <param name="TheLibrary">The library from which the type originated.</param>
        /// <param name="aType">The type to scan.</param>
        /// <returns>The new type info.</returns>
        public static TypeInfo ScanType(IL.ILLibrary TheLibrary, Type aType)
        {
            if (TheLibrary.TypeInfos.Where(x => x.UnderlyingType.Equals(aType)).Count() > 0)
            {
                return(TheLibrary.TypeInfos.Where(x => x.UnderlyingType.Equals(aType)).First());
            }

            string   typeName    = aType.Name;
            TypeInfo newTypeInfo = new TypeInfo()
            {
                UnderlyingType = aType
            };

            TheLibrary.TypeInfos.Add(newTypeInfo);

            {
                object[] CustAttrs = aType.GetCustomAttributes(false);
                foreach (object aCustAttr in CustAttrs)
                {
                    if (!aCustAttr.GetType().AssemblyQualifiedName.Contains("mscorlib"))
                    {
                        if (!IL.ILLibrary.SpecialClasses.ContainsKey(aCustAttr.GetType()))
                        {
                            IL.ILLibrary.SpecialClasses.Add(aCustAttr.GetType(), new List <TypeInfo>());
                        }
                        IL.ILLibrary.SpecialClasses[aCustAttr.GetType()].Add(newTypeInfo);
                    }
                }
            }

            //Ignore all internal data of types from mscorlib except for value types such as
            //  int, uint etc. and associated pointer types
            if (!aType.AssemblyQualifiedName.Contains("mscorlib"))
            {
                // All Fields
                System.Reflection.FieldInfo[] allFields = aType.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
                foreach (System.Reflection.FieldInfo aFieldInfo in allFields)
                {
                    if (aFieldInfo.DeclaringType.Equals(newTypeInfo.UnderlyingType))
                    {
                        newTypeInfo.FieldInfos.Add(new FieldInfo()
                        {
                            UnderlyingInfo = aFieldInfo
                        });
                    }
                }

                // Plugged / Unplugged Methods
                System.Reflection.MethodInfo[] allMethods = aType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).ToArray();

                foreach (System.Reflection.MethodInfo aMethodInfo in allMethods)
                {
                    if (aMethodInfo.DeclaringType.Equals(aType))
                    {
                        MethodInfo newMethodInfo = new MethodInfo()
                        {
                            UnderlyingInfo = aMethodInfo,
                            PlugAttribute  = (Attributes.PluggedMethodAttribute)aMethodInfo.GetCustomAttribute(typeof(Attributes.PluggedMethodAttribute))
                        };
                        newTypeInfo.MethodInfos.Add(newMethodInfo);

                        object[] CustAttrs = aMethodInfo.GetCustomAttributes(false);
                        foreach (object aCustAttr in CustAttrs)
                        {
                            if (!aCustAttr.GetType().AssemblyQualifiedName.Contains("mscorlib"))
                            {
                                if (!IL.ILLibrary.SpecialMethods.ContainsKey(aCustAttr.GetType()))
                                {
                                    IL.ILLibrary.SpecialMethods.Add(aCustAttr.GetType(), new List <MethodInfo>());
                                }
                                IL.ILLibrary.SpecialMethods[aCustAttr.GetType()].Add(newMethodInfo);
                            }
                        }
                    }
                }

                // Plugged / unplugged Constructors
                ConstructorInfo[] allConstructors = aType.GetConstructors(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                                                    .ToArray();
                foreach (ConstructorInfo aConstructorInfo in allConstructors)
                {
                    if (aConstructorInfo.DeclaringType.Equals(aType))
                    {
                        MethodInfo newMethodInfo = new MethodInfo()
                        {
                            UnderlyingInfo = aConstructorInfo,
                            PlugAttribute  = (Attributes.PluggedMethodAttribute)aConstructorInfo.GetCustomAttribute(typeof(Attributes.PluggedMethodAttribute))
                        };
                        newTypeInfo.MethodInfos.Add(newMethodInfo);

                        object[] CustAttrs = aConstructorInfo.GetCustomAttributes(false);
                        foreach (object aCustAttr in CustAttrs)
                        {
                            if (!aCustAttr.GetType().AssemblyQualifiedName.Contains("mscorlib"))
                            {
                                if (!IL.ILLibrary.SpecialMethods.ContainsKey(aCustAttr.GetType()))
                                {
                                    IL.ILLibrary.SpecialMethods.Add(aCustAttr.GetType(), new List <MethodInfo>());
                                }
                                IL.ILLibrary.SpecialMethods[aCustAttr.GetType()].Add(newMethodInfo);
                            }
                        }
                    }
                }
            }

            return(newTypeInfo);
        }
Exemple #6
0
        public override bool LinkISO(IL.ILLibrary TheLibrary, LinkInformation LinkInfo)
        {
            bool OK = true;

            string BinPath = LinkInfo.ISOPath.Replace(".iso", ".bin");
            string ElfPath = LinkInfo.ISOPath.Replace(".iso", ".elf");

            StreamWriter ASMWriter = new StreamWriter(LinkInfo.ASMPath, false);

            StringBuilder CommandLineArgsBuilder = new StringBuilder();

            CommandLineArgsBuilder.Append("--fatal-warnings -EL -Os -T \"" + LinkInfo.LinkScriptPath + "\" -o \"" + ElfPath + "\"");

            StringBuilder LinkScript = new StringBuilder();

            LinkScript.Append(@"ENTRY(Kernel_Start)
OUTPUT_ARCH(mips)

SECTIONS {
   . = 0x" + Options.BaseAddress.ToString("X8") + @";

   .text : AT(ADDR(.text) - " + Options.LoadOffset.ToString() + @") {
");

            for (int i = 0; i < LinkInfo.SequencedASMBlocks.Count; i++)
            {
                LinkScript.AppendLine(string.Format("       \"{0}\" (.text);", LinkInfo.SequencedASMBlocks[i].ObjectOutputFilePath));
                ASMWriter.WriteLine(File.ReadAllText(LinkInfo.SequencedASMBlocks[i].ASMOutputFilePath));
            }


            LinkScript.AppendLine(@"
          * (.text);
   }

    . = ALIGN(0x4);
   .data : AT(ADDR(.data) - " + Options.LoadOffset.ToString() + @") {
          * (.data*);
   }

   . = ALIGN(0x4);
   .bss : AT(ADDR(.bss) - " + Options.LoadOffset.ToString() + @") {
          * (.bss*);
   }
}
");

            ASMWriter.Close();

            File.WriteAllText(LinkInfo.LinkScriptPath, LinkScript.ToString());
            OK = Utilities.ExecuteProcess(LinkInfo.LdWorkingDir, Path.Combine(LinkInfo.ToolsPath, @"MIPS\mips-linux-gnu-ld.exe"), CommandLineArgsBuilder.ToString(), "Ld");

            if (OK)
            {
                if (File.Exists(BinPath))
                {
                    File.Delete(BinPath);
                }

                OK = Utilities.ExecuteProcess(Options.OutputPath, Path.Combine(LinkInfo.ToolsPath, @"MIPS\mips-linux-gnu-objcopy.exe"), string.Format("-O binary \"{0}\" \"{1}\"", ElfPath, BinPath), "MIPS:ObjCopy");

                if (OK)
                {
                    if (File.Exists(LinkInfo.MapPath))
                    {
                        File.Delete(LinkInfo.MapPath);
                    }

                    OK = Utilities.ExecuteProcess(Options.OutputPath, Path.Combine(LinkInfo.ToolsPath, @"MIPS\mips-linux-gnu-objdump.exe"), string.Format("--wide --syms \"{0}\"", ElfPath), "MIPS:ObjDump", false, LinkInfo.MapPath);
                }
            }

            return(OK);
        }
Exemple #7
0
 public override bool LinkELF(IL.ILLibrary TheLibrary, LinkInformation LinkInfo)
 {
     return(false);
 }
Exemple #8
0
        /// <summary>
        /// Executes the Drivers Compiler using the specified logging methods.
        /// </summary>
        /// <param name="messageHandler">The handler for outputting ordinary messages.</param>
        /// <param name="warningHandler">The handler for outputting warning messages.</param>
        /// <param name="errorHandler">The handler for outputting error messages.</param>
        /// <returns>Returns an error code.</returns>
        public static ErrorCode Execute(
            Logger.LogMessageEventHandler messageHandler,
            Logger.LogWarningEventHandler warningHandler,
            Logger.LogErrorEventHandler errorHandler)
        {
            ErrorCode result = ErrorCode.NoError;

            Logger.OnLogMessage += messageHandler;
            Logger.OnLogWarning += warningHandler;
            Logger.OnLogError   += errorHandler;

            Options.Format();

            DateTime startTime = DateTime.Now;

            Logger.LogMessage("", 0, "Driver compiler started  @ " + startTime.ToLongTimeString());
            Logger.LogMessage("", 0, "Library path             = \"" + Options.LibraryPath + "\"");
            Logger.LogMessage("", 0, "Output path              = \"" + Options.OutputPath + "\"");
            Logger.LogMessage("", 0, "Tools path               = \"" + Options.ToolsPath + "\"");
            Logger.LogMessage("", 0, "Target architecture      = \"" + Options.TargetArchitecture + "\"");
            Logger.LogMessage("", 0, "Build mode               = " + Enum.GetName(typeof(Options.BuildModes), Options.BuildMode));
            Logger.LogMessage("", 0, "Link mode                = " + Enum.GetName(typeof(Options.LinkModes), Options.LinkMode));
            Logger.LogMessage("", 0, "Base address             = " + Options.BaseAddress.ToString());
            Logger.LogMessage("", 0, "Load offset              = " + Options.LoadOffset.ToString());

            // IL Library       - In a list of libraries returned to the higher-level control app (this app)
            //                    from Library Loader
            //  : Type Info         - In a list of types in the IL Library
            //      : Field Info        - In a list of static and non-static fields in the Type Info
            //      : Method Info       - In a list of methods in the Type Info
            //          : Variable Info     - In a list of variables in the Method Info
            //  : IL Block          - In a list of blocks in the IL Library and held against the origin Method Info
            //      : IL Op             - In a list of ops in the IL Block
            //
            // ASM Library      - In a list of libraries returned to the higher-level control app (this app)
            //                    from IL Compiler
            //  : ASM Block         - In a list of blocks in the ASM Library and held against the origin IL Block
            //      : ASM Op            - In a list of ops in the ASM Block
            //
            // Options          - Compiler options used throughout the compiler

            // Library loader   - Loads IL Libraries to be compiled
            //      - Type Scanner     - Loads all the Type Infos, Field Infos and Method Infos.
            // IL Compiler      - Manages the IL compile stage
            //      - IL Reader        - Loads IL ops from IL Methods in IL Types. Also loads plug info.
            //      - IL Preprocessor  - Pre-scans IL ops to find things like necessary branching labels.
            //                           Also handles injecting any necessary IL ops in such a way that
            //                           IL integrity is maintained.
            //      - IL Scanner       - Converts IL ops to ASM ops
            // ASM Compiler     - Manages the ASM compile stage
            //      - ASM Preprocessor - Pre-scans the ASM ops to store things like debug info or perform
            //                           optimisation
            //      - ASM Processor    - Converts ASM ops into ASM text then runs the assembly code compiler (e.g. NASM)
            // Link Manager     - Manages the linker stage. Links together all the object files using "ld".

            // To think about:
            //      - Try-catch-finally blocks
            //      - GC (inc. wrapping try-finally, calls to inc/dec)
            //      - Release / Debug IL (differences? Potential issues?)

            // Resultant thoughts from above:
            //      - IL labels based on IL Op index NOT IL op offset
            //      - IL Preprocessor handle injecting any IL ops inc. try-catch-finally, GC stuff and special
            //        class / method stuff (e.g. static variables, static constructors etc.)
            //      - IL Preprocessor needs to maintain the integrity of the IL so that no assumption are made
            //          so that Release mode IL also works

            // TODO:
            //      - Check for unchanged methods (in IL Preprocessor) and exclude them from recompile

            Tuple <bool, string> ValidateOptions_Result = Options.Validate();

            if (ValidateOptions_Result.Item1)
            {
                try
                {
                    TargetArchitecture.Init();

                    IL.ILLibrary TheLibrary = LibraryLoader.LoadILLibrary(Options.LibraryPath);

                    CompileResult ILCompileResult = IL.ILCompiler.Compile(TheLibrary);

                    if (ILCompileResult == CompileResult.OK ||
                        ILCompileResult == CompileResult.PartialFailure)
                    {
                        CompileResult ASMCompileResult = ASM.ASMCompiler.Compile(TheLibrary);

                        if (ASMCompileResult == CompileResult.OK)
                        {
                            CompileResult LinkResult = LinkManager.Link(TheLibrary);

                            if (LinkResult == CompileResult.OK)
                            {
                                if (ILCompileResult == CompileResult.PartialFailure)
                                {
                                    result = ErrorCode.ILCompilerFailed;
                                }

                                //Success
                                Logger.LogMessage("", 0, "Compilation succeeded.");
                            }
                            else
                            {
                                //Fail
                                Logger.LogError(Errors.Linker_LinkFailed_ErrorCode, "", 0,
                                                Errors.ErrorMessages[Errors.Linker_LinkFailed_ErrorCode]);
                                result = ErrorCode.LinkerFailed;
                            }
                        }
                        else
                        {
                            //Fail
                            Logger.LogError(Errors.ASMCompiler_CompileFailed_ErrorCode, "", 0,
                                            Errors.ErrorMessages[Errors.ASMCompiler_CompileFailed_ErrorCode]);
                            result = ErrorCode.ASMCompilerFailed;
                        }
                    }
                    else
                    {
                        //Fail
                        Logger.LogError(Errors.ILCompiler_CompileFailed_ErrorCode, "", 0,
                                        Errors.ErrorMessages[Errors.ILCompiler_CompileFailed_ErrorCode]);
                        result = ErrorCode.ILCompilerFailed;
                    }
                }
                catch (NullReferenceException ex)
                {
                    Logger.LogError(Errors.ILCompiler_NullRefException_ErrorCode, "", 0,
                                    string.Format(
                                        Errors.ErrorMessages[Errors.ILCompiler_NullRefException_ErrorCode],
                                        ex.Message, ex.StackTrace));
                    result = ErrorCode.ILCompilerFailed;
                }
                catch (Exception ex)
                {
                    Logger.LogError(Errors.ILCompiler_UnexpectedException_ErrorCode, "", 0,
                                    string.Format(
                                        Errors.ErrorMessages[Errors.ILCompiler_UnexpectedException_ErrorCode],
                                        ex.Message, ex.StackTrace));
                    result = ErrorCode.ILCompilerFailed;
                }
            }
            else
            {
                //Fail
                Logger.LogError(Errors.PreReqs_OptionsInvalid_ErrorCode, "", 0,
                                string.Format(
                                    Errors.ErrorMessages[Errors.PreReqs_OptionsInvalid_ErrorCode],
                                    ValidateOptions_Result.Item2));
                result = ErrorCode.InvalidOptions;
            }

            DateTime endTime = DateTime.Now;

            Logger.LogMessage("", 0, "Driver compiler finished @ " + endTime.ToLongTimeString());
            Logger.LogMessage("", 0, "            Compile time : " + (endTime - startTime).ToString());
            Logger.LogMessage("", 0, "              Error code : " + System.Enum.GetName(typeof(ErrorCode), result));

            return(result);
        }
Exemple #9
0
        public override bool LinkELF(IL.ILLibrary TheLibrary, LinkInformation LinkInfo)
        {
            StringBuilder CommandLineArgsBuilder = new StringBuilder();

            if (!LinkInfo.ExecutableOutput)
            {
                CommandLineArgsBuilder.Append("-shared ");
            }
            CommandLineArgsBuilder.Append("-L .\\Output -T \"" + LinkInfo.LinkScriptPath + "\" -o \"" + LinkInfo.BinPath + "\"");

            StreamWriter ASMWriter = new StreamWriter(LinkInfo.ASMPath, false);

            StringBuilder LinkScript = new StringBuilder();

            LinkScript.Append((LinkInfo.ExecutableOutput ? "ENTRY(" + LinkInfo.EntryPoint + ")\r\n" : "") +
                              @"GROUP(");

            LinkScript.Append(string.Join(" ", LinkInfo.SequencedASMBlocks
                                          .Where(x => File.Exists(x.ObjectOutputFilePath))
                                          .Select(x => "\"" + x.ObjectOutputFilePath + "\"")));

            LinkScript.Append(@")

");
            if (LinkInfo.depLibNames.Count > 0)
            {
                LinkScript.Append("GROUP(");
                LinkScript.Append(string.Join(" ", LinkInfo.depLibNames.Select(x => "-l" + x)));
                LinkScript.Append(")");
            }

            LinkScript.AppendLine(@"

SECTIONS {
   . = 0x" + (0x40000000 + (LinkInfo.depLibNames.Count * 0x1000)).ToString("X2") + @";

   .text : {
");

            for (int i = 0; i < LinkInfo.SequencedASMBlocks.Count; i++)
            {
                LinkScript.AppendLine(string.Format("       \"{0}\" (.text);", LinkInfo.SequencedASMBlocks[i].ObjectOutputFilePath));
                ASMWriter.WriteLine(File.ReadAllText(LinkInfo.SequencedASMBlocks[i].ASMOutputFilePath));
            }


            LinkScript.AppendLine(@"
          * (.text);
          * (.rodata*);
   }

   . = ALIGN(0x1000);
   .data : AT(ADDR(.data)) {
          * (.data*);
   }

   . = ALIGN(0x1000);
   .bss : AT(ADDR(.bss)) {
          * (.bss*);
   }
}
");
            ASMWriter.Close();

            File.WriteAllText(LinkInfo.LinkScriptCmdPath, CommandLineArgsBuilder.ToString());
            File.WriteAllText(LinkInfo.LinkScriptPath, LinkScript.ToString());
            return(Utilities.ExecuteProcess(LinkInfo.LdWorkingDir, Path.Combine(LinkInfo.ToolsPath, @"Cygwin\ld.exe"), CommandLineArgsBuilder.ToString(), "Ld"));
        }
Exemple #10
0
        public override bool LinkISO(IL.ILLibrary TheLibrary, LinkInformation LinkInfo)
        {
            bool OK = true;

            StreamWriter ASMWriter = new StreamWriter(LinkInfo.ASMPath, false);

            StringBuilder CommandLineArgsBuilder = new StringBuilder();

            CommandLineArgsBuilder.Append("--fatal-warnings -T \"" + LinkInfo.LinkScriptPath + "\" -o \"" + LinkInfo.BinPath + "\"");

            StringBuilder LinkScript = new StringBuilder();

            LinkScript.Append(@"ENTRY(Kernel_Start)
OUTPUT_FORMAT(elf32-i386)

GROUP(");

            LinkScript.Append(string.Join(" ", LinkInfo.SequencedASMBlocks
                                          .Where(x => File.Exists(x.ObjectOutputFilePath))
                                          .Select(x => "\"" + x.ObjectOutputFilePath + "\"")));

            LinkScript.AppendLine(@")

SECTIONS {
   /* The kernel will live at 3GB + 1MB in the virtual
      address space, which will be mapped to 1MB in the
      physical address space. */
   . = 0x" + Options.BaseAddress.ToString("X8") + @";

   .text : AT(ADDR(.text) - " + Options.LoadOffset.ToString() + @") {
");

            for (int i = 0; i < LinkInfo.SequencedASMBlocks.Count; i++)
            {
                LinkScript.AppendLine(string.Format("       \"{0}\" (.text);", LinkInfo.SequencedASMBlocks[i].ObjectOutputFilePath));
                ASMWriter.WriteLine(File.ReadAllText(LinkInfo.SequencedASMBlocks[i].ASMOutputFilePath));
            }


            LinkScript.AppendLine(@"
          * (.text);
          * (.rodata*);
   }

   . = ALIGN(0x1000);
   .data : AT(ADDR(.data) - " + Options.LoadOffset.ToString() + @") {
          * (.data*);
   }

   . = ALIGN(0x1000);
   .bss : AT(ADDR(.bss) - " + Options.LoadOffset.ToString() + @") {
          * (.bss*);
   }
}
");

            ASMWriter.Close();

            File.WriteAllText(LinkInfo.LinkScriptPath, LinkScript.ToString());
            OK = Utilities.ExecuteProcess(LinkInfo.LdWorkingDir, Path.Combine(LinkInfo.ToolsPath, @"Cygwin\ld.exe"), CommandLineArgsBuilder.ToString(), "Ld");

            if (OK)
            {
                if (File.Exists(LinkInfo.ISOPath))
                {
                    File.Delete(LinkInfo.ISOPath);
                }

                OK = Utilities.ExecuteProcess(Options.OutputPath, LinkInfo.ISOGenPath,
                                              string.Format("4 \"{0}\" \"{1}\" true \"{2}\"", LinkInfo.ISOPath, LinkInfo.ISOLinuxPath, LinkInfo.ISODirPath), "ISO9660Generator");

                if (OK)
                {
                    if (File.Exists(LinkInfo.MapPath))
                    {
                        File.Delete(LinkInfo.MapPath);
                    }

                    OK = Utilities.ExecuteProcess(Options.OutputPath, Path.Combine(LinkInfo.ToolsPath, @"Cygwin\objdump.exe"), string.Format("--wide --syms \"{0}\"", LinkInfo.BinPath), "ObjDump", false, LinkInfo.MapPath);
                }
            }

            return(OK);
        }