Пример #1
0
        public int Generate(
            string wszInputFilePath,
            string bstrInputFileContents,
            string wszDefaultNamespace,
            IntPtr[] rgbOutputFileContents,
            out uint pcbOutput,
            IVsGeneratorProgress pGenerateProgress)
        {
            string xResult;

            using (var xInput = new StringReader(bstrInputFileContents))
            {
                using (var xOut = new StringWriter())
                {
                    try
                    {
                        var xAssembler = new Assembler.Assembler();
                        try
                        {
                            var xGen = new AsmGenerator();
                            xGen.Generate(xInput, xOut);
                            xResult = $"Generated at {DateTime.Now} {Environment.NewLine} {Environment.NewLine} {xOut} {Environment.NewLine}";
                        }
                        finally
                        {
                            Assembler.Assembler.ClearCurrentInstance();
                        }
                    }
                    catch (Exception ex)
                    {
                        var xSB = new StringBuilder();
                        xSB.Append(xOut);
                        xSB.AppendLine();

                        for (Exception e = ex; e != null; e = e.InnerException)
                        {
                            xSB.AppendLine(e.Message);
                        }
                        xResult = xSB.ToString();
                    }
                }
            }

            rgbOutputFileContents[0] = IntPtr.Zero;
            pcbOutput = 0;
            var xBytes = Encoding.UTF8.GetBytes(xResult);

            if (xBytes.Length > 0)
            {
                rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(xBytes.Length);
                Marshal.Copy(xBytes, 0, rgbOutputFileContents[0], xBytes.Length);
                pcbOutput = (uint)xBytes.Length;
            }

            return(VSConstants.S_OK);
        }
Пример #2
0
        static void Main(string[] aArgs)
        {
            try {
                var xCLI   = new XSharp.Build.CliProcessor(aArgs);
                var xGen   = new AsmGenerator();
                var xFiles = new List <string>();

                // Parse arguments
                foreach (var xArg in aArgs)
                {
                    if (xArg.StartsWith("-"))
                    {
                        string xOpt = xArg.Substring(1).ToUpper();
                        throw new Exception("No matching switch found: " + xArg);
                    }
                    else
                    {
                        if (Directory.Exists(xArg))
                        {
                            string xPath = Path.GetFullPath(xArg);
                            xFiles.AddRange(Directory.GetFiles(xPath, "*.xs"));
                        }
                        else if (File.Exists(xArg))
                        {
                            xFiles.Add(Path.GetFullPath(xArg));
                        }
                        else
                        {
                            throw new Exception("Not a valid file or directory: " + xArg);
                        }
                    }
                }

                // Generate output
                foreach (var xFile in xFiles)
                {
                    Console.WriteLine(xFile);
                    xGen.GenerateToFiles(xFile);
                }

                // Finalize
                Console.WriteLine("Done.");
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
                System.Threading.Thread.Sleep(3000);
                Environment.Exit(1);
            }
        }
Пример #3
0
        public void Initialize()
        {
            uint xSig = 0x1BADB002;

            DataMembers.Add(new DataIfNotDefined("ELF_COMPILATION"));
            DataMembers.Add(new DataMember("MultibootSignature", new uint[]
            {
                xSig
            }));
            uint xFlags = 0x10007;

            DataMembers.Add(new DataMember("MultibootFlags", xFlags));
            DataMembers.Add(new DataMember("MultibootChecksum", (int)(0 - (xFlags + xSig))));
            DataMembers.Add(new DataMember("MultibootHeaderAddr", ElementReference.New("MultibootSignature")));
            DataMembers.Add(new DataMember("MultibootLoadAddr", ElementReference.New("MultibootSignature")));
            DataMembers.Add(new DataMember("MultibootLoadEndAddr", ElementReference.New("_end_code")));
            DataMembers.Add(new DataMember("MultibootBSSEndAddr", ElementReference.New("_end_code")));
            DataMembers.Add(new DataMember("MultibootEntryAddr", ElementReference.New("Kernel_Start")));
            DataMembers.Add(new DataMember("", 0));
            DataMembers.Add(new DataMember("", 800, 600, 32));
            DataMembers.Add(new DataEndIfDefined());

            DataMembers.Add(new DataIfDefined("ELF_COMPILATION"));
            xFlags = 0x00007;
            DataMembers.Add(new DataMember("MultibootSignature", new uint[]
            {
                xSig
            }));
            DataMembers.Add(new DataMember("MultibootFlags", xFlags));
            DataMembers.Add(new DataMember("MultibootChecksum", (int)(0 - (xFlags + xSig))));
            DataMembers.Add(new DataMember("", 0, 0, 0, 0, 0));
            DataMembers.Add(new DataMember("", 0));
            DataMembers.Add(new DataMember("", 800, 600, 32));
            DataMembers.Add(new DataEndIfDefined());

            //graphics info fields
            DataMembers.Add(new DataMember("MultibootGraphicsRuntime_VbeModeInfoAddr", 1 << 2));
            DataMembers.Add(new DataMember("MultibootGraphicsRuntime_VbeControlInfoAddr", 1 << 0));
            DataMembers.Add(new DataMember("MultibootGraphicsRuntime_VbeMode", 0));

            // memory
            DataMembers.Add(new DataMember("MultiBootInfo_Memory_High", 0));
            DataMembers.Add(new DataMember("MultiBootInfo_Memory_Low", 0));
            DataMembers.Add(new DataMember("Before_Kernel_Stack", new byte[0x50000]));
            DataMembers.Add(new DataMember("Kernel_Stack", new byte[0]));
            DataMembers.Add(new DataMember("MultiBootInfo_Structure", new uint[1]));

            // constants
            DataMembers.Add(new DataMember(@"__uint2double_const", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x41 }));
            DataMembers.Add(new DataMember(@"__ulong2double_const", 0x5F800000));
            DataMembers.Add(new DataMember(@"__doublesignbit", 0x8000000000000000));
            DataMembers.Add(new DataMember(@"__floatsignbit", 0x80000000));

            if (mComPort > 0)
            {
                new Define("DEBUGSTUB");
            }

            // This is our first entry point. Multiboot uses this as Cosmos entry point.
            new Label("Kernel_Start", isGlobal: true);
            XS.Set(XSRegisters.ESP, "Kernel_Stack");

            // Displays "Cosmos" in top left. Used to make sure Cosmos is booted in case of hang.
            // ie bootloader debugging. This must be the FIRST code, even before setup so we know
            // we are being called properly by the bootloader and that if there are problems its
            // somwhere in our code, not the bootloader.
            WriteDebugVideo("Cosmos pre boot");

            // For when using Bochs, causes a break ASAP on entry after initial Cosmos display.
            //new LiteralAssemblerCode("xchg bx, bx");

            // CLI ASAP
            WriteDebugVideo("Clearing interrupts.");
            XS.ClearInterruptFlag();


            WriteDebugVideo("Begin multiboot info.");
            new LiteralAssemblerCode("%ifndef EXCLUDE_MULTIBOOT_MAGIC");
            new Comment(this, "MultiBoot compliant loader provides info in registers: ");
            new Comment(this, "EBX=multiboot_info ");
            new Comment(this, "EAX=0x2BADB002 - check if it's really Multiboot-compliant loader ");
            new Comment(this, "                ;- copy mb info - some stuff for you  ");
            new Comment(this, "BEGIN - Multiboot Info");
            new Mov
            {
                DestinationRef        = ElementReference.New("MultiBootInfo_Structure"),
                DestinationIsIndirect = true,
                SourceReg             = RegistersEnum.EBX
            };
            XS.Add(XSRegisters.EBX, 4);
            XS.Set(XSRegisters.EAX, XSRegisters.EBX, sourceIsIndirect: true);
            new Mov
            {
                DestinationRef        = ElementReference.New("MultiBootInfo_Memory_Low"),
                DestinationIsIndirect = true,
                SourceReg             = RegistersEnum.EAX
            };
            XS.Add(XSRegisters.EBX, 4);
            XS.Set(XSRegisters.EAX, XSRegisters.EBX, sourceIsIndirect: true);
            new Mov
            {
                DestinationRef        = ElementReference.New("MultiBootInfo_Memory_High"),
                DestinationIsIndirect = true,
                SourceReg             = RegistersEnum.EAX
            };
            new Comment(this, "END - Multiboot Info");
            new LiteralAssemblerCode("%endif");
            WriteDebugVideo("Creating GDT.");
            CreateGDT();

            WriteDebugVideo("Configuring PIC");
            ConfigurePIC();

            WriteDebugVideo("Creating IDT.");
            CreateIDT();

            new Comment("Set graphics fields");
            new Mov {
                DestinationReg = XSRegisters.EBX, SourceRef = ElementReference.New("MultiBootInfo_Structure"), SourceIsIndirect = true
            };
            new Mov {
                DestinationReg = XSRegisters.EAX, SourceReg = XSRegisters.EBX, SourceIsIndirect = true, SourceDisplacement = 72
            };
            new Mov {
                DestinationRef = ElementReference.New("MultibootGraphicsRuntime_VbeControlInfoAddr"), DestinationIsIndirect = true, SourceReg = XSRegisters.EAX
            };
            new Mov {
                DestinationReg = XSRegisters.EAX, SourceReg = XSRegisters.EBX, SourceIsIndirect = true, SourceDisplacement = 76
            };
            new Mov {
                DestinationRef = ElementReference.New("MultibootGraphicsRuntime_VbeModeInfoAddr"), DestinationIsIndirect = true, SourceReg = XSRegisters.EAX
            };
            new Mov {
                DestinationReg = XSRegisters.EAX, SourceReg = XSRegisters.EBX, SourceIsIndirect = true, SourceDisplacement = 80
            };
            new Mov {
                DestinationRef = ElementReference.New("MultibootGraphicsRuntime_VbeMode"), DestinationIsIndirect = true, SourceReg = XSRegisters.EAX
            };

            //WriteDebugVideo("Initializing SSE.");
            //new Comment(this, "BEGIN - SSE Init");
            //// CR4[bit 9]=1, CR4[bit 10]=1, CR0[bit 2]=0, CR0[bit 1]=1
            //XS.Mov(XSRegisters.EAX, XSRegisters.Registers.CR4);
            //XS.Or(XSRegisters.EAX, 0x100);
            //XS.Mov(XSRegisters.CR4, XSRegisters.Registers.EAX);
            //XS.Mov(XSRegisters.EAX, XSRegisters.Registers.CR4);
            //XS.Or(XSRegisters.EAX, 0x200);
            //XS.Mov(XSRegisters.CR4, XSRegisters.Registers.EAX);
            //XS.Mov(XSRegisters.EAX, XSRegisters.Registers.CR0);

            //XS.And(XSRegisters.EAX, 0xfffffffd);
            //XS.Mov(XSRegisters.CR0, XSRegisters.Registers.EAX);
            //XS.Mov(XSRegisters.EAX, XSRegisters.Registers.CR0);

            //XS.And(XSRegisters.EAX, 1);
            //XS.Mov(XSRegisters.CR0, XSRegisters.Registers.EAX);
            //new Comment(this, "END - SSE Init");

            if (mComPort > 0)
            {
                WriteDebugVideo("Initializing DebugStub.");
                XS.Call(AsmMarker.Labels[AsmMarker.Type.DebugStub_Init]);
            }

            // Jump to Kernel entry point
            WriteDebugVideo("Jumping to kernel.");
            XS.Call(EntryPointName);

            new Comment(this, "Kernel done - loop till next IRQ");
            XS.Label(".loop");
            XS.ClearInterruptFlag();
            XS.Halt();
            XS.Jump(".loop");

            if (mComPort > 0)
            {
                var xGen = new AsmGenerator();

                var xGenerateAssembler =
                    new Action <object>(i =>
                {
                    if (i is StreamReader)
                    {
                        var xAsm = xGen.Generate((StreamReader)i);
                        CurrentInstance.Instructions.AddRange(xAsm.Instructions);
                        CurrentInstance.DataMembers.AddRange(xAsm.DataMembers);
                    }
                    else if (i is string)
                    {
                        var xAsm = xGen.Generate((string)i);
                        CurrentInstance.Instructions.AddRange(xAsm.Instructions);
                        CurrentInstance.DataMembers.AddRange(xAsm.DataMembers);
                    }
                    else
                    {
                        throw new Exception("Object type '" + i.ToString() + "' not supported!");
                    }
                });
                if (ReadDebugStubFromDisk)
                {
                    foreach (var xFile in Directory.GetFiles(CosmosPaths.DebugStubSrc, "*.xs"))
                    {
                        xGenerateAssembler(xFile);
                    }
                }
                else
                {
                    foreach (var xManifestName in typeof(ReferenceHelper).Assembly.GetManifestResourceNames())
                    {
                        if (!xManifestName.EndsWith(".xs", StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }
                        using (var xStream = typeof(ReferenceHelper).Assembly.GetManifestResourceStream(xManifestName))
                        {
                            using (var xReader = new StreamReader(xStream))
                            {
                                xGenerateAssembler(xReader);
                            }
                        }
                    }
                }
                OnAfterEmitDebugStub();
            }
            else
            {
                XS.Label(AsmMarker.Labels[AsmMarker.Type.DebugStub_Step]);
                XS.Return();
            }

            // Start emitting assembly labels
            CurrentInstance.EmitAsmLabels = true;
        }
        /// <summary>
        /// Timer of launching operations
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpTimer_Tick(object sender, EventArgs e)
        {
            //according to the operation to be executed
            switch (operation)
            {
            case ProcessOperation.Check:
                //The errors of all the diagrams are checked
                List <DiagramError> errors = new List <DiagramError>();
                foreach (Diagram diagram in this.project.Functions)
                {
                    Generator.CheckDiagram(diagram, errors);
                }
                //If there are errors, it is reported
                if (errors.Count != 0)
                {
                    bool onlyWarnings = false;
                    //the errors are checked
                    foreach (DiagramError error in errors)
                    {
                        //If any of the errors is not a warning
                        if (error.Type == ErrorType.Error)
                        {
                            onlyWarnings         = true;
                            this.opTimer.Enabled = false;
                            //The Close button is enabled
                            this.bClose.Enabled = true;
                            //The error is displayed
                            this.pbCheckDiagram.Image    = this.icons.Images[(int)OperationState.Error];
                            this.lCheckDiagram.Text      = ProcessMessages.CHECKDIAGRAM_ERROR;
                            this.lCheckDiagram.ForeColor = Color.FromArgb(208, 0, 0);
                            break;
                        }
                    }
                    //If they are only warnings
                    if (!onlyWarnings)
                    {
                        //The warning message is displayed
                        this.pbCheckDiagram.Image    = this.icons.Images[(int)OperationState.Warning];
                        this.lCheckDiagram.Text      = ProcessMessages.CHECKDIAGRAM_WARNING;
                        this.lCheckDiagram.ForeColor = Color.FromArgb(200, 140, 0);
                        //it passes to the following operation
                        this.operation            = ProcessOperation.Generate;
                        this.pbGenerateCode.Image = this.icons.Images[(int)OperationState.Running];
                    }
                    //The error event is launched
                    if (this.DiagramErrors != null)
                    {
                        this.DiagramErrors(this, new ProcessEventArgs(errors));
                    }
                }
                else
                {
                    this.pbCheckDiagram.Image = this.icons.Images[(int)OperationState.Finish];
                    this.lCheckDiagram.Text   = ProcessMessages.CHECKDIAGRAM_OK;
                    //it passes to the following operation
                    this.operation            = ProcessOperation.Generate;
                    this.pbGenerateCode.Image = this.icons.Images[(int)OperationState.Running];
                }
                break;

            case ProcessOperation.Generate:
                //Generates the source code for the diagrams
                try
                {
                    // The code is generated
                    AsmGenerator.GenerateCode(this.project.MainFunction, this.project.Subfunctions, this.project.Variables, this.project.AsmFile);
                    this.lGenerateCode.Text   = ProcessMessages.GENERATECODE_OK;
                    this.pbGenerateCode.Image = this.icons.Images[(int)OperationState.Finish];
                    //it passes to the following operation
                    this.operation           = ProcessOperation.Compile;
                    this.pbCompileCode.Image = this.icons.Images[(int)OperationState.Running];
                }
                catch { }
                break;

            case ProcessOperation.Compile:
                //The generated source code is compiled
                try
                {
                    //The project is compiled
                    if (AsmCompiler.Compile(this.project.AsmFile))
                    {
                        this.lCompileCode.Text   = ProcessMessages.COMPILECODE_OK;
                        this.pbCompileCode.Image = this.icons.Images[(int)OperationState.Finish];
                        //it passes to the following operation
                        this.operation            = ProcessOperation.Program;
                        this.opTimer.Interval     = 50;
                        this.pbProgramMoway.Image = this.icons.Images[(int)OperationState.Running];
                    }
                    else
                    {
                        this.opTimer.Enabled = false;
                        //The Close button is enabled
                        this.bClose.Enabled = true;
                        //The error is displayed
                        this.pbCompileCode.Image    = this.icons.Images[(int)OperationState.Error];
                        this.lCompileCode.ForeColor = Color.FromArgb(208, 0, 0);
                        this.lCompileCode.Text      = ProcessMessages.COMPILECODE_ERROR;
                    }
                }
                //Code compilation failed
                catch (CompilerException ex)
                {
                    this.opTimer.Enabled = false;
                    //The Close button is enabled
                    this.bClose.Enabled = true;
                    //The error is displayed
                    this.pbCompileCode.Image    = this.icons.Images[(int)OperationState.Error];
                    this.lCompileCode.ForeColor = Color.FromArgb(208, 0, 0);
                    switch (ex.Message)
                    {
                    case "File not found":
                        this.lCompileCode.Text = ProcessMessages.FILE_NOT_FOUND;
                        break;

                    case "Access denied":
                        this.lCompileCode.Text = ProcessMessages.ACCES_DENIED;
                        break;

                    default:
                        this.lCompileCode.Text = ProcessMessages.COMPILECODE_ERROR;
                        break;
                    }
                }
                break;

            case ProcessOperation.Program:
                //Launches the recording process
                this.opTimer.Enabled = false;
                //MOway Driver events are logged
                Controller.Controller mController = Controller.Controller.GetController();
                mController.ProgrammingProgress  += new ProgressEventHandler(MController_ProgrammingProgress);
                mController.ProgrammingCompleted += new EventHandler(MController_ProgrammingCompleted);
                mController.ProgrammingCanceled  += new EventHandler(MController_ProgrammingCanceled);
                try
                {
                    //It checks the memory of the micro...
                    int response = mController.CheckPicMemory(this.project.HexFile);
                    if (response == 1)
                    {
                        //A confirmation is requested
                        if (DialogResult.No == MowayMessageBox.Show(ProcessMessages.HEX_TOO_LARGE_201 + "\r\n" + ProcessMessages.CONTINUE, ProcessMessages.PROGRAM, MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                        {
                            //The Close button is enabled
                            this.bClose.Enabled = true;
                            //The error is displayed
                            this.pbProgramMoway.Image    = this.icons.Images[(int)OperationState.Error];
                            this.lProgramMoway.ForeColor = Color.FromArgb(208, 0, 0);
                            this.lProgramMoway.Text      = ProcessMessages.MEMORY_ERROR;
                            return;
                        }
                    }
                    else if (response == 2)
                    {
                        //A confirmation is requested
                        if (DialogResult.No == MowayMessageBox.Show(ProcessMessages.HEX_TOO_LARGE_202 + "\r\n" + ProcessMessages.CONTINUE, ProcessMessages.PROGRAM, MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                        {
                            //The Close button is enabled
                            this.bClose.Enabled = true;
                            //The error is displayed
                            this.pbProgramMoway.Image    = this.icons.Images[(int)OperationState.Error];
                            this.lProgramMoway.ForeColor = Color.FromArgb(208, 0, 0);
                            this.lProgramMoway.Text      = ProcessMessages.MEMORY_ERROR;
                            return;
                        }
                    }
                    //Timer is enabled to limit the recording process to 15 seconds
                    this.tProgramLimited.Enabled = true;
                    //It launches the recording of the mOway
                    mController.ProgramMoway(this.project.HexFile);
                }
                //Timer is enabled to limit the recording process to 15 seconds
                catch (ControllerException ex)
                {
                    //The Close button is enabled
                    this.bClose.Enabled = true;
                    //The error is displayed
                    this.pbProgramMoway.Image    = this.icons.Images[(int)OperationState.Error];
                    this.lProgramMoway.ForeColor = Color.FromArgb(208, 0, 0);
                    switch (ex.Message)
                    {
                    case "File not found":
                        this.lProgramMoway.Text = ProcessMessages.FILE_NOT_FOUND;
                        break;

                    case "Moway disconnected":
                        this.lProgramMoway.Text = ProcessMessages.MOWAY_DISCONNECTED;
                        break;

                    case "Moway busy":
                        this.lProgramMoway.Text = ProcessMessages.MOWAY_BUSY;
                        break;

                    default:
                        this.lProgramMoway.Text = ProcessMessages.PROGRAMMOWAY_ERROR;
                        break;
                    }
                }
                break;

            case ProcessOperation.Close:
                //Close the form
                this.DialogResult = DialogResult.OK;
                this.Close();
                break;
            }
        }
Пример #5
0
        private static void Main(string[] aArgs)
        {
            try
            {
                // Parse arguments
                var xCLI = new Build.CliProcessor();
                xCLI.Parse(aArgs);

                try
                {
                    var xGen = new AsmGenerator();

                    bool   xAppend     = false;
                    string xOutputPath = null;

                    // Options
                    var xUserComments = xCLI["UserComments", "UC"];
                    if (xUserComments != null)
                    {
                        xGen.EmitUserComments = xUserComments.Check("ON", new string[] { "ON", "OFF" }) == "ON";
                    }
                    //
                    var xSourceCode = xCLI["SourceCode", "SC"];
                    if (xSourceCode != null)
                    {
                        xGen.EmitSourceCode = xSourceCode.Check("ON", new string[] { "ON", "OFF" }) == "ON";
                    }
                    //
                    var xOutput = xCLI["Out", "O"];
                    if (xOutput != null)
                    {
                        xOutputPath = xOutput.Value;
                    }
                    //
                    xAppend = xCLI["Append", "A"] != null;
                    if (xAppend && xOutput == null)
                    {
                        throw new Exception("Use of -Append requires use of -Out.");
                    }

                    // Plugins
                    var xPlugins = xCLI.GetSwitches("PlugIn");
                    foreach (var xPlugin in xPlugins)
                    {
                        // TODO Load plugins
                    }

                    // List of source files
                    var xFiles      = new List <string>();
                    var xAssemblies = new List <Assembly>();
                    foreach (var xArg in xCLI.Args)
                    {
                        string xVal = xArg.Value;

                        if (Directory.Exists(xVal))
                        {
                            // If dir specified, find all .xs files
                            string xPath = Path.GetFullPath(xVal);
                            xFiles.AddRange(Directory.GetFiles(xPath, "*.xs"));
                        }
                        else if (File.Exists(xVal))
                        {
                            string xExt = Path.GetExtension(xVal).ToUpper();
                            if (xExt == ".XS")
                            {
                                xFiles.Add(Path.GetFullPath(xVal));
                            }
                            else if (xExt == ".DLL")
                            {
                                xAssemblies.Add(Assembly.LoadFrom(xVal));
                            }
                            else
                            {
                                throw new Exception("Not a valid file type: " + xVal);
                            }
                        }
                        else
                        {
                            throw new Exception("Not a valid file or directory: " + xVal);
                        }
                    }

                    if (xCLI["Gen2"] != null)
                    {
                        foreach (var xFile in xFiles)
                        {
                            using (var xIn = File.OpenText(xFile))
                            {
                                if (!xAppend)
                                {
                                    xOutputPath = Path.ChangeExtension(xFile, ".asm");
                                }

                                using (var xOut = File.CreateText(xOutputPath))
                                {
                                    Console.WriteLine("Processing file: " + xFile);
                                    Compiler xCompiler;

                                    try
                                    {
                                        xCompiler = new Compiler(xOut);
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine(e);
                                        throw;
                                    }
                                    try
                                    {
                                        xCompiler.Emit(xIn);
                                        var temp = Console.BackgroundColor;
                                        Console.BackgroundColor = ConsoleColor.Green;
                                        Console.WriteLine("File processed");
                                        Console.BackgroundColor = temp;
                                    }
                                    catch (Exception e)
                                    {
                                        var temp = Console.BackgroundColor;
                                        Console.BackgroundColor = ConsoleColor.Red;
                                        Console.WriteLine(e);
                                        Console.BackgroundColor = temp;
                                        throw;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            // Generate output
                            foreach (var xFile in xFiles)
                            {
                                var xReader = File.OpenText(xFile);
                                if (xAppend)
                                {
                                    xGen.Generate(xReader, File.AppendText(xOutputPath));
                                }
                                else if (xFiles.Count == 1 && xOutputPath != null)
                                {
                                    xGen.Generate(File.OpenText(xFile), File.CreateText(xOutputPath));
                                }
                                else
                                {
                                    Console.WriteLine(xFile);
                                    xGen.GenerateToFiles(xFile);
                                }
                            }

                            // Generate output from embedded resources
                            foreach (var xAssembly in xAssemblies)
                            {
                                TextWriter xWriter = null;
                                if (!xAppend)
                                {
                                    var xDestination = Path.ChangeExtension(xAssembly.Location, "asm");
                                    xWriter = new StreamWriter(File.Create(xDestination));
                                }

                                foreach (var xResource in xAssembly.GetManifestResourceNames()
                                         .Where(r => r.EndsWith(".xs", StringComparison.OrdinalIgnoreCase)))
                                {
                                    var xStream = xAssembly.GetManifestResourceStream(xResource);
                                    xGen.GenerateToFile(xResource, new StreamReader(xStream), xWriter);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }

                    // Finalize
                    Console.WriteLine("Done.");
                }
                catch (Exception ex)
                {
                    if (xCLI["WaitOnError"] != null)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Waiting on error. Press Enter to exit.");
                        Console.WriteLine("Exception: " + ex.ToString());
                        Console.ReadLine();
                    }
                    Environment.Exit(-1);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Argument parse error:\r\n" + ex);
                Environment.Exit(-2);
            }
        }
Пример #6
0
        public void Initialize(bool enableVBE, string VBEResolution)
        {
            uint xSig = 0xe85250d6;

            //Multiboot header
            DataMembers.Add(new DataMember("align", "8", true));
            DataMembers.Add(new DataMember("MultibootHeader", Array.Empty <byte>()));
            DataMembers.Add(new DataMember("MultibootSignature", new uint[] { xSig }));
            DataMembers.Add(new DataMember("MultibootArchitecture", 0));
            DataMembers.Add(new DataMember("MultibootLenght", "MultibootHeaderEnd - MultibootHeader", typeof(uint)));
            DataMembers.Add(new DataMember("MultibootChecksum", "0x100000000 - (0xe85250d6 + 0 + (MultibootHeaderEnd - MultibootHeader))", typeof(uint)));

            if (enableVBE)
            {
                try
                {
                    string[] res = VBEResolution.Split('x');

                    //Framebuffer Tag
                    DataMembers.Add(new DataMember("align", "8", true));
                    DataMembers.Add(new DataMember("MultibootFramebufferTag", Array.Empty <byte>()));
                    DataMembers.Add(new DataMember("MultibootFramebufferType", (ushort)5));
                    DataMembers.Add(new DataMember("MultibootFramebufferOptional", (ushort)1));
                    DataMembers.Add(new DataMember("MultibootFramebufferLenght", "MultibootFramebufferTagEnd - MultibootFramebufferTag", typeof(uint)));
                    DataMembers.Add(new DataMember("", int.Parse(res[0])));
                    DataMembers.Add(new DataMember("", int.Parse(res[1])));
                    DataMembers.Add(new DataMember("", int.Parse(res[2])));

                    DataMembers.Add(new DataMember("MultibootFramebufferTagEnd", Array.Empty <byte>()));
                }
                catch
                {
                    Console.WriteLine("VBE Resolution must be this format: 1920x1080x32");
                }
            }

            // memory
            DataMembers.Add(new DataMember("align", "8", true));
            DataMembers.Add(new DataMember("MultibootMemoryTag", Array.Empty <byte>()));
            DataMembers.Add(new DataMember("MultibootMemoryTagType", (ushort)2));
            DataMembers.Add(new DataMember("MultibootMemoryTagOptional", (ushort)1));
            DataMembers.Add(new DataMember("MultibootMemoryTagLenght", "MultibootMemoryTagEnd - MultibootMemoryTag", typeof(uint)));
            DataMembers.Add(new DataMember("MultibootHeaderAddr", ElementReference.New("MultibootSignature")));
            DataMembers.Add(new DataMember("MultibootLoadAddr", ElementReference.New("MultibootSignature")));
            DataMembers.Add(new DataMember("MultibootLoadEndAddr", ElementReference.New("_end_code")));
            DataMembers.Add(new DataMember("MultibootBSSEndAddr", ElementReference.New("_end_code")));
            DataMembers.Add(new DataMember("MultibootMemoryTagEnd", Array.Empty <byte>()));

            //Entry Address
            DataMembers.Add(new DataMember("align", "8", true));
            DataMembers.Add(new DataMember("MultibootEntryTag", Array.Empty <byte>()));
            DataMembers.Add(new DataMember("MultibootEntryTagType", (ushort)3));
            DataMembers.Add(new DataMember("MultibootEntryTagOptional", (ushort)1));
            DataMembers.Add(new DataMember("MultibootEntryTagLenght", "MultibootEntryTagEnd - MultibootEntryTag", typeof(uint)));
            DataMembers.Add(new DataMember("MultibootEntryAddr", ElementReference.New("Kernel_Start")));
            DataMembers.Add(new DataMember("MultibootEntryTagEnd", Array.Empty <byte>()));

            //End Tag
            DataMembers.Add(new DataMember("align", "8", true));
            DataMembers.Add(new DataMember("MultibootEndTag", Array.Empty <byte>()));
            DataMembers.Add(new DataMember("MultibootEndTagType", (ushort)0));
            DataMembers.Add(new DataMember("MultibootEndTagOptional", (ushort)0));
            DataMembers.Add(new DataMember("MultibootEndTagEnd", Array.Empty <byte>()));

            DataMembers.Add(new DataMember("MultibootHeaderEnd", Array.Empty <byte>()));

            //memory
            DataMembers.Add(new DataMember("align", "16", true));
            DataMembers.Add(new DataMember("Before_Kernel_Stack", new byte[0x50000]));
            DataMembers.Add(new DataMember("align", "16", true));
            DataMembers.Add(new DataMember("Kernel_Stack", Array.Empty <byte>()));
            DataMembers.Add(new DataMember("MultiBootInfo_Structure", new uint[1]));

            // constants
            DataMembers.Add(new DataMember("align", "16", true));
            DataMembers.Add(new DataMember(@"__uint2double_const", new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x41 }));
            DataMembers.Add(new DataMember("align", "16", true));
            DataMembers.Add(new DataMember(@"__ulong2double_const", 0x5F800000));
            DataMembers.Add(new DataMember("align", "16", true));
            DataMembers.Add(new DataMember(@"__doublesignbit", 0x8000000000000000));
            DataMembers.Add(new DataMember("align", "16", true));
            DataMembers.Add(new DataMember(@"__floatsignbit", 0x80000000));

            if (mComPort > 0)
            {
                new Define("DEBUGSTUB");
            }

            // This is our first entry point. Multiboot uses this as Cosmos entry point.
            new Label("Kernel_Start", isGlobal: true);
            XS.Set(ESP, "Kernel_Stack");

            // Displays "Cosmos" in top left. Used to make sure Cosmos is booted in case of hang.
            // ie bootloader debugging. This must be the FIRST code, even before setup so we know
            // we are being called properly by the bootloader and that if there are problems its
            // somwhere in our code, not the bootloader.
            WriteDebugVideo("Cosmos pre boot");

            // For when using Bochs, causes a break ASAP on entry after initial Cosmos display.
            //new LiteralAssemblerCode("xchg bx, bx");

            // CLI ASAP
            WriteDebugVideo("Clearing interrupts.");
            XS.ClearInterruptFlag();


            WriteDebugVideo("Begin multiboot info.");
            new LiteralAssemblerCode("%ifndef EXCLUDE_MULTIBOOT_MAGIC");
            new Comment(this, "MultiBoot compliant loader provides info in registers: ");
            new Comment(this, "EBX=multiboot_info ");
            new Comment(this, "EAX=0x36d76289 - check if it's really Multiboot2-compliant loader ");
            new Comment(this, "                ;- copy mb info - some stuff for you  ");
            new Comment(this, "BEGIN - Multiboot Info");
            new Mov
            {
                DestinationRef        = ElementReference.New("MultiBootInfo_Structure"),
                DestinationIsIndirect = true,
                SourceReg             = RegistersEnum.EBX
            };

            XS.Call("SystemVoidCosmosCoreMultiboot2Init");

            new Comment(this, "END - Multiboot Info");
            new LiteralAssemblerCode("%endif");
            WriteDebugVideo("Creating GDT.");
            CreateGDT();

            WriteDebugVideo("Configuring PIC");
            ConfigurePIC();

            WriteDebugVideo("Creating IDT.");
            CreateIDT();

            //WriteDebugVideo("Initializing SSE.");
            //new Comment(this, "BEGIN - SSE Init");
            //// CR4[bit 9]=1, CR4[bit 10]=1, CR0[bit 2]=0, CR0[bit 1]=1
            //XS.Mov(XSRegisters.EAX, XSRegisters.Registers.CR4);
            //XS.Or(XSRegisters.EAX, 0x100);
            //XS.Mov(XSRegisters.CR4, XSRegisters.Registers.EAX);
            //XS.Mov(XSRegisters.EAX, XSRegisters.Registers.CR4);
            //XS.Or(XSRegisters.EAX, 0x200);
            //XS.Mov(XSRegisters.CR4, XSRegisters.Registers.EAX);
            //XS.Mov(XSRegisters.EAX, XSRegisters.Registers.CR0);

            //XS.And(XSRegisters.EAX, 0xfffffffd);
            //XS.Mov(XSRegisters.CR0, XSRegisters.Registers.EAX);
            //XS.Mov(XSRegisters.EAX, XSRegisters.Registers.CR0);

            //XS.And(XSRegisters.EAX, 1);
            //XS.Mov(XSRegisters.CR0, XSRegisters.Registers.EAX);
            //new Comment(this, "END - SSE Init");

            if (mComPort > 0)
            {
                WriteDebugVideo("Initializing DebugStub.");
                XS.Call(AsmMarker.Labels[AsmMarker.Type.DebugStub_Init]);
            }

            //Initiate Memory
            WriteDebugVideo("Initiating Memory");
            XS.Call(LabelName.Get(GCImplementationRefs.InitRef));

            // Jump to Kernel entry point
            WriteDebugVideo("Jumping to kernel.");
            XS.Call(EntryPointName);

            new Comment(this, "Kernel done - loop till next IRQ");
            XS.Label(".loop");
            XS.ClearInterruptFlag();
            XS.Halt();
            XS.Jump(".loop");

            if (mComPort > 0)
            {
                var xGen = new AsmGenerator();

                void GenerateAssembler(Assembler assembler)
                {
                    CurrentInstance.Instructions.AddRange(assembler.Instructions);
                    CurrentInstance.DataMembers.AddRange(assembler.DataMembers);
                }

                if (ReadDebugStubFromDisk)
                {
                    foreach (var xFile in Directory.GetFiles(CosmosPaths.DebugStubSrc, "*.xs"))
                    {
                        GenerateAssembler(xGen.Generate(xFile));
                    }
                }
                else
                {
                    foreach (var xManifestName in typeof(ReferenceHelper).Assembly.GetManifestResourceNames())
                    {
                        if (!xManifestName.EndsWith(".xs", StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }
                        using (var xStream = typeof(ReferenceHelper).Assembly.GetManifestResourceStream(xManifestName))
                        {
                            using (var xReader = new StreamReader(xStream))
                            {
                                GenerateAssembler(xGen.Generate(xReader));
                            }
                        }
                    }
                }
                OnAfterEmitDebugStub();
            }
            else
            {
                XS.Label(AsmMarker.Labels[AsmMarker.Type.DebugStub_Step]);
                XS.Return();
            }

            // Start emitting assembly labels
            CurrentInstance.EmitAsmLabels = true;
        }
Пример #7
0
        /// <summary>
        /// Timer of launching operations
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpTimer_Tick(object sender, EventArgs e)
        {
            //according to the operation to be executed
            switch (operation)
            {
            case ProcessOperation.Check:
                //The errors of all the diagrams are checked
                List <DiagramError> errors = new List <DiagramError>();
                foreach (Diagram diagram in this.project.Functions)
                {
                    Generator.CheckDiagram(diagram, errors);
                }
                //If there are errors, it is reported
                if (errors.Count != 0)
                {
                    bool onlyWarnings = false;
                    //the errors are checked
                    foreach (DiagramError error in errors)
                    {
                        //If any of the errors is not a warning
                        if (error.Type == ErrorType.Error)
                        {
                            onlyWarnings         = true;
                            this.opTimer.Enabled = false;
                            //The Close button is enabled
                            this.bClose.Enabled = true;
                            //The error is displayed
                            this.pbCheckDiagram.Image    = this.icons.Images[(int)OperationState.Error];
                            this.lCheckDiagram.Text      = ProcessMessages.CHECKDIAGRAM_ERROR;
                            this.lCheckDiagram.ForeColor = Color.FromArgb(208, 0, 0);
                            break;
                        }
                    }
                    //If they are only warnings
                    if (!onlyWarnings)
                    {
                        //The warning message is displayed
                        this.pbCheckDiagram.Image    = this.icons.Images[(int)OperationState.Warning];
                        this.lCheckDiagram.Text      = ProcessMessages.CHECKDIAGRAM_WARNING;
                        this.lCheckDiagram.ForeColor = Color.FromArgb(200, 140, 0);
                        //it passes to the following operation
                        this.operation            = ProcessOperation.Generate;
                        this.pbGenerateCode.Image = this.icons.Images[(int)OperationState.Running];
                    }
                    //The error event is launched
                    if (this.DiagramErrors != null)
                    {
                        this.DiagramErrors(this, new ProcessEventArgs(errors));
                    }
                }
                else
                {
                    this.pbCheckDiagram.Image = this.icons.Images[(int)OperationState.Finish];
                    this.lCheckDiagram.Text   = ProcessMessages.CHECKDIAGRAM_OK;
                    //it passes to the following operation
                    this.operation            = ProcessOperation.Generate;
                    this.pbGenerateCode.Image = this.icons.Images[(int)OperationState.Running];
                }
                break;

            case ProcessOperation.Generate:
                //Generates the source code for the diagrams
                try
                {
                    //It generates the code
                    AsmGenerator.GenerateCode(this.project.MainFunction, this.project.Subfunctions, this.project.Variables, this.project.AsmFile);
                    this.lGenerateCode.Text   = ProcessMessages.GENERATECODE_OK;
                    this.pbGenerateCode.Image = this.icons.Images[(int)OperationState.Finish];
                    //it passes to the following operation
                    this.operation           = ProcessOperation.Compile;
                    this.pbCompileCode.Image = this.icons.Images[(int)OperationState.Running];
                }
                catch { }
                break;

            case ProcessOperation.Compile:
                //se compila el código fuente generado
                try
                {
                    //The generated source code is compiled
                    if (AsmCompiler.Compile(this.project.AsmFile))
                    {
                        this.lCompileCode.Text   = ProcessMessages.COMPILECODE_OK;
                        this.pbCompileCode.Image = this.icons.Images[(int)OperationState.Finish];
                        //it passes to the following operation
                        this.operation        = ProcessOperation.Close;
                        this.opTimer.Interval = 1000;
                    }
                    else
                    {
                        this.opTimer.Enabled = false;
                        //The Close button is enabled
                        this.bClose.Enabled = true;
                        //The error is displayed
                        this.pbCompileCode.Image    = this.icons.Images[(int)OperationState.Error];
                        this.lCompileCode.ForeColor = Color.FromArgb(208, 0, 0);
                        this.lCompileCode.Text      = ProcessMessages.COMPILECODE_ERROR;
                    }
                }
                //Code compilation failed
                catch (CompilerException ex)
                {
                    this.opTimer.Enabled = false;
                    //The Close button is enabled
                    this.bClose.Enabled = true;
                    //The error is displayed
                    this.pbCompileCode.Image    = this.icons.Images[(int)OperationState.Error];
                    this.lCompileCode.ForeColor = Color.FromArgb(208, 0, 0);
                    switch (ex.Message)
                    {
                    case "File not found":
                        this.lCompileCode.Text = ProcessMessages.FILE_NOT_FOUND;
                        break;

                    case "Access denied":
                        this.lCompileCode.Text = ProcessMessages.ACCES_DENIED;
                        break;

                    default:
                        this.lCompileCode.Text = ProcessMessages.COMPILECODE_ERROR;
                        break;
                    }
                }
                break;

            case ProcessOperation.Close:
                //Close the form
                this.DialogResult = DialogResult.OK;
                this.Close();
                break;
            }
        }