コード例 #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            string path    = textBox1.Text;
            var    hexfile = new HexFile(path);

            richTextBox1.Clear();
            richTextBox1.AppendLine(hexfile.blocks.Count.ToString());
            int num = 0;

            foreach (var b in hexfile.blocks)
            {
                num++;
                richTextBox1.AppendLine($"Block {num}\t{b.StartAddress} - {b.EndAddress}");

                for (int i = 0; i < b.Data.Count; i++)
                {
                    var bin = Convert.ToString(b.Data[i], 2);
                    richTextBox1.AppendLine($"{b.StartAddress + i}\t{bin.PadLeft(16, '0')}\t{b.Data[i]}\t{b.Data[i]:X}");
                }
                richTextBox1.AppendLine();
            }
            var prog = new Programmer("COM6", hexfile.blocks);

            prog.BurnBlocks();
        }
コード例 #2
0
ファイル: COutput.cs プロジェクト: jncronin/tysila
        private static void EmitStringInit(TypeSpec tdr, Stream hmsw, Stream cmsw,
                                           List <string> advance_defines, List <string> external_defines, List <string> header_funcs, Target ass)
        {
            // Emit a string creation instruction of the form:
            // void CreateString(System_String **obj, const char *s)

            string init_func = "void CreateString(struct System_String **obj, const char *s)";

            header_funcs.Add(init_func + ";");

            HexFile.writeStr(cmsw, init_func);
            HexFile.writeStr(cmsw, "{");
            HexFile.writeStr(cmsw, "    int i;");
            HexFile.writeStr(cmsw, "    int l = s == NULL ? 0 : strlen(s);");
            HexFile.writeStr(cmsw, "    " + ass.GetCType(tdr.m.SystemChar) + " *p;");
            HexFile.writeStr(cmsw, "    *obj = (struct System_String *)malloc(sizeof(struct System_String) + l * sizeof(" +
                             ass.GetCType(tdr.m.SystemChar) + "));");
            HexFile.writeStr(cmsw, "    Init_System_String(*obj);");
            HexFile.writeStr(cmsw, "    (*obj)->m_stringLength = l;");
            HexFile.writeStr(cmsw, "    p = &((*obj)->m_firstChar);");
            //HexFile.writeStr(cmsw, "    p = (" + ass.GetCType(BaseType_Type.Char) +
            //    " *)(*obj + sizeof(struct System_String));");
            HexFile.writeStr(cmsw, "    for(i = 0; i < l; i++)");
            HexFile.writeStr(cmsw, "        p[i] = (" + ass.GetCType(tdr.m.SystemChar) + ")s[i];");
            HexFile.writeStr(cmsw, "}");
            HexFile.writeStr(cmsw);
        }
コード例 #3
0
ファイル: Downloader.cs プロジェクト: Cougar/HomeAutomation
 public Downloader(HexFile hf, DaemonConnection dc, byte receiveID, bool isBiosUpdate)
 {
     this.hf = hf;
     this.dc = dc;
     this.receiveID = receiveID;
     this.isBiosUpdate = isBiosUpdate;
 }
コード例 #4
0
ファイル: MainWindow.cs プロジェクト: daschewie/FoenixIDE
        // Convert a Hex file to PGX
        // Header is PGX,1,4 byte jump address
        private void ConvertHexToPGXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog
            {
                Filter          = "Hex Files|*.hex",
                Title           = "Select a Hex File",
                CheckFileExists = true
            };

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                MemoryRAM temporaryRAM = new MemoryRAM(0, 4 * 1024 * 1024);
                HexFile.Load(temporaryRAM, dialog.FileName, 0, out int DataStartAddress, out int DataLength);
                // write the file
                string outputFileName = Path.ChangeExtension(dialog.FileName, "PGX");

                byte[] buffer = new byte[DataLength];
                temporaryRAM.CopyIntoBuffer(DataStartAddress, buffer, 0, DataLength);
                using (BinaryWriter writer = new BinaryWriter(File.Open(outputFileName, FileMode.Create)))
                {
                    // 8 byte header
                    writer.Write((byte)'P');
                    writer.Write((byte)'G');
                    writer.Write((byte)'X');
                    writer.Write((byte)1);
                    writer.Write(DataStartAddress);
                    writer.Write(buffer);
                }
            }
        }
コード例 #5
0
        public void ResetCPU(bool ResetMemory)
        {
            CPU.Halt();

            gpu.Refresh();

            // This fontset is loaded just in case the kernel doesn't provide one.
            gpu.LoadFontSet("Foenix", @"Resources\Bm437_PhoenixEGA_8x8.bin", 0, CharacterSet.CharTypeCodes.ASCII_PET, CharacterSet.SizeCodes.Size8x8);

            if (Configuration.Current.StartUpHexFile.EndsWith(".fnxml", true, null))
            {
                FoeniXmlFile fnxml = new FoeniXmlFile(MemoryManager, Resources, CPUWindow.Instance.breakpoints);
                fnxml.Load(Configuration.Current.StartUpHexFile);
            }
            else
            {
                Configuration.Current.StartUpHexFile = HexFile.Load(MemoryManager, Configuration.Current.StartUpHexFile);
                if (Configuration.Current.StartUpHexFile != null)
                {
                    if (ResetMemory)
                    {
                        lstFile = new ListFile(Configuration.Current.StartUpHexFile);
                    }
                    else
                    {
                        // TODO: We should really ensure that there are no duplicated PC in the list
                        ListFile tempList = new ListFile(Configuration.Current.StartUpHexFile);
                        lstFile.Lines.InsertRange(0, tempList.Lines);
                    }
                }
            }

            // If the reset vector is not set in Bank 0, but it is set in Bank 18, then copy bank 18 into bank 0.
            if (MemoryManager.ReadLong(0xFFE0) == 0 && MemoryManager.ReadLong(0x18_FFE0) != 0)
            //if (MemoryManager.ReadLong(0xFFFC) == 0 && MemoryManager.ReadLong(0x18_FFFC) != 0)
            {
                MemoryManager.Copy(0x180000, MemoryMap.RAM_START, MemoryMap.PAGE_SIZE);
                // See if lines of code exist in the 0x18_0000 to 0x18_FFFF block
                List <DebugLine> copiedLines = new List <DebugLine>();
                if (lstFile.Lines.Count > 0)
                {
                    List <DebugLine> tempLines = new List <DebugLine>();
                    foreach (DebugLine line in lstFile.Lines)
                    {
                        if (line.PC >= 0x18_0000 && line.PC < 0x19_0000)
                        {
                            DebugLine dl = (DebugLine)line.Clone();
                            dl.PC -= 0x18_0000;
                            copiedLines.Add(dl);
                        }
                    }
                }
                if (copiedLines.Count > 0)
                {
                    lstFile.Lines.InsertRange(0, copiedLines);
                }
            }
            CPU.Reset();
        }
コード例 #6
0
ファイル: Downloader.cs プロジェクト: Cougar/HomeAutomation
 public int calcCRC(HexFile hf)
 {
     int crc=0;
     for (ulong i=hf.getAddrLower(); i <= hf.getAddrUpper(); i++) {
         crc = crc16_update(crc, hf.getByte(i));
     }
     return crc;
 }
コード例 #7
0
ファイル: Downloader.cs プロジェクト: Cougar/HomeAutomation
 public Downloader(HexFile hf, DaemonConnection dc, byte receiveID, bool isBiosUpdate, bool HWID_INUSE, uint hwid)
 {
     this.hf = hf;
     this.dc = dc;
     this.receiveID = receiveID;
     this.isBiosUpdate = isBiosUpdate;
     this.hwid = hwid;
     this.HWID_INUSE = HWID_INUSE;
 }
コード例 #8
0
ファイル: COutput.cs プロジェクト: jncronin/tysila
        private static void EmitArrayInit(TypeSpec ts, string tname, Stream hmsw, Stream cmsw,
                                          List <string> header_funcs, Target ass)
        {
            string typestr        = ass.GetCType(ts);
            string init_func_name = "void* Create_" + tname + "_Array(struct __array **arr_obj, int32_t length)";

            /* Arrays have four pieces of memory allocated:
             * - The array superblock
             * - The lobounds array
             * - The sizes array
             * - The actual array data
             *
             * We do not allocate the last 3, as they may need to be placed at a different virtual address
             * when relocated - let the implementation decide this
             *
             * Code is:
             *
             * struct __array
             * {
             *     intptr           __vtbl;
             *     int32_t          __object_id;
             *     int64_t          __mutex_lock;
             *     int32_t          rank;
             *     int32_t          elem_size;
             *     intptr           lobounds;
             *     intptr           sizes;
             *     intptr           inner_array;
             * } __attribute__((__packed__));
             *
             * void Create_X_Array(__array **arr_obj, int32_t num_elems)
             * {
             *     *arr_obj = (__array *)malloc(sizeof(arr_obj));
             *     (*arr_obj)->rank = 1;
             * }
             */

            //int elem_size = ass.GetPackedSizeOf(new Signature.Param(baseType_Type));

            header_funcs.Add(init_func_name + ";");
            HexFile.writeStr(cmsw, init_func_name);
            HexFile.writeStr(cmsw, "{");
            HexFile.writeStr(cmsw, "    *arr_obj = (struct __array *)malloc(sizeof(struct __array));");
            HexFile.writeStr(cmsw, "    (*arr_obj)->__vtbl = Get_Symbol_Addr(\"" + ts.SzArray.MangleType() + "\");");
            HexFile.writeStr(cmsw, "    (*arr_obj)->__mutex_lock = 0;");
            HexFile.writeStr(cmsw, "    (*arr_obj)->rank = 1;");
            HexFile.writeStr(cmsw, "    (*arr_obj)->elem_size = sizeof(" + typestr + ");");
            HexFile.writeStr(cmsw, "    (*arr_obj)->elemtype = Get_Symbol_Addr(\"" + ts.MangleType() + "\");");
            HexFile.writeStr(cmsw, "    (*arr_obj)->lobounds = (INTPTR)(intptr_t)malloc(sizeof(int32_t));");
            HexFile.writeStr(cmsw, "    (*arr_obj)->sizes = (INTPTR)(intptr_t)malloc(sizeof(int32_t));");
            HexFile.writeStr(cmsw, "    (*arr_obj)->inner_array = (INTPTR)(intptr_t)malloc(length * sizeof(" + typestr + "));");
            HexFile.writeStr(cmsw, "    *(int32_t *)(intptr_t)((*arr_obj)->lobounds) = 0;");
            HexFile.writeStr(cmsw, "    *(int32_t *)(intptr_t)((*arr_obj)->sizes) = length;");
            HexFile.writeStr(cmsw, "    return((void *)(intptr_t)((*arr_obj)->inner_array));");
            HexFile.writeStr(cmsw, "}");
            HexFile.writeStr(cmsw);
        }
コード例 #9
0
ファイル: HexBoard.cs プロジェクト: drukhadze/Flasher
        public static HexBoard From(HexFile file)
        {
            var res = new HexBoard();

            foreach (var line in file.Lines)
            {
                for (int index = 0; index < line.Data.Length; index++)
                {
                    var bt = line.Data[index];
                    res[line.Address + index] = bt;
                }
            }
            return(res);
        }
コード例 #10
0
 public void HexFile_Constructor()
 {
     //https://www.youtube.com/watch?v=KKiG5NJkqXs
     //https://docs.microsoft.com/en-us/visualstudio/test/using-shims-to-isolate-your-application-from-other-assemblies-for-unit-testing?view=vs-2019
     using (ShimsContext.Create())
     {
         //Arrange
         System.IO.Fakes.ShimFile.ReadAllLinesString = s => new string[] { "1", "1", "1" };
         //System.Fakes.ShimDateTime.NowGet = () =>   { return new DateTime(fixedYear, 1, 1); };
         System.Fakes.ShimDateTime.NowGet = () => new DateTime(2000, 1, 1);
         //Act
         var target = new HexFile("fake.path");
         Y2KChecker.Check();
         //Assert
         Assert.AreEqual(3, target.Record.Length);
     }
 }
コード例 #11
0
ファイル: COutput.cs プロジェクト: jncronin/tysila
 private static void EmitArrayType(Stream hmsw, Target ass, MetadataStream m)
 {
     HexFile.writeStr(hmsw, "struct __array");
     HexFile.writeStr(hmsw, "{");
     HexFile.writeStr(hmsw, "    INTPTR           __vtbl;");
     HexFile.writeStr(hmsw, "    int64_t          __mutex_lock;");
     HexFile.writeStr(hmsw, "    INTPTR           elemtype;");
     HexFile.writeStr(hmsw, "    INTPTR           lobounds;");
     HexFile.writeStr(hmsw, "    INTPTR           sizes;");
     HexFile.writeStr(hmsw, "    INTPTR           inner_array;");
     HexFile.writeStr(hmsw, "    INTPTR           rank;");
     HexFile.writeStr(hmsw, "    int32_t          elem_size;");
     //if (packed_structs)
     //    HexFile.writeStr(hmsw, "} __attribute__((__packed__));");
     //else
     HexFile.writeStr(hmsw, "};");
     HexFile.writeStr(hmsw);
 }
コード例 #12
0
    public static HexFile ReadHexFile(string path, out string s)
    {
        HexFile hexFile = new HexFile();

        s = "";
        Debug.Log("Hello");
        if (!System.IO.File.Exists(path))
        {
            s = "不存在相应的目录";
            throw new Exception("目录文件不存在");
        }
        else
        {
            using (var stream = File.OpenRead(path))
            {
                hexFile.hexData = new byte[stream.Length];
                stream.Read(hexFile.hexData, 0, hexFile.hexData.Length);
            }

            Debug.Log(hexFile.hexData.Length);
            return(hexFile);
        }
    }
コード例 #13
0
ファイル: NuSystem.cs プロジェクト: drone84/Nu256
        public void Reset()
        {
            CPU.Halt();

            Cls();
            gpu.Refresh();

            // Load the ROM data from disk. On the real system, the ROMs are not accessible by the CPU
            // and will be copied to RAM by VICKY
            MemoryRAM flashROM = new MemoryRAM(0, 16 * 65536);

            this.ReadyHandler = Monitor;
            HexFile.Load(flashROM, @"ROMs\kernel.hex");
            flashROM.Copy(0, Memory.SRAM, 0, 2 * 65536);
            CPU.Reset();

            //CPUTest test= new CPUTest(this);
            //test.BeginTest(0xf81000);

            this.TickTimer.Interval = 1000 / 60;
            this.TickTimer.Elapsed += TickTimer_Elapsed;
            this.TickTimer.Enabled  = true;
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: ATtinyTeenageRiot/TinyHID
        static void Main(string[] args)
        {
            Loader ldr;

            try
            {
                ldr = new Loader();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            if (args.Length == 1 && File.Exists(args[0]) ||
                args.Length == 2 && args[1] == "notleave" && File.Exists(args[0]))
            {
                // Write
                HexFile file     = new HexFile(args[0]);
                byte[]  programm = new byte[Loader.LOADERSTART];
                for (int i = 0; i < programm.Length; i++)
                {
                    programm[i] = 0xff;
                }
                file.Fill(programm);
                try
                {
                    DateTime now = DateTime.Now;
                    ldr.WriteFlash(programm, 0);
                    int ellapsed = (int)(DateTime.Now - now).TotalMilliseconds;
                    Console.WriteLine("Done in {0} ms", ellapsed);
                    if (args.Length != 2 || args[1] != "notleave")
                    {
                        ldr.LeaveBootloader();
                    }
                    Console.WriteLine("Success");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return;
                }
                return;
            }
            else if (args.Length == 2 && args[0] == "reload" && File.Exists(args[1]))
            {
                string exe      = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
                string reloader = Path.Combine(Path.GetDirectoryName(exe), "reloader.hex");
                if (!File.Exists(reloader))
                {
                    Console.WriteLine("reloader.hex not exists");
                    return;
                }
                // create image for writing
                byte[] programm = new byte[Loader.LOADERSTART];
                // fill image with 0xff
                for (int i = 0; i < programm.Length; i++)
                {
                    programm[i] = 0xff;
                }
                // write jump to reloader
                programm[0] = 0x20;
                programm[1] = 0xc0;
                HexFile rel = new HexFile(reloader);
                // write reloader
                rel.Fill(programm);

                if (rel.End > RELOADER_INFO)
                {
                    Console.WriteLine("reloader too big");
                }

                HexFile hf      = new HexFile(args[1]);
                long    address = hf.Offset;
                long    size    = Loader.FLASHSIZE - address;
                if (size + RELOADER_BOOTLOADER_DATA > Loader.LOADERSTART)
                {
                    Console.WriteLine("bootloader is too big to fit");
                    return;
                }
                hf.Fill(programm, RELOADER_BOOTLOADER_DATA - address);
                programm[RELOADER_INFO_OFFSET]     = (byte)(address & 0xff);
                programm[RELOADER_INFO_OFFSET + 1] = (byte)((address >> 8) & 0xff);
                ushort crc = Loader.Crc16(programm, RELOADER_BOOTLOADER_DATA, (int)size);
                programm[RELOADER_INFO_CRC]     = (byte)(crc & 0xff);
                programm[RELOADER_INFO_CRC + 1] = (byte)((crc >> 8) & 0xff);
                HexFile ot = new HexFile();
                ot.Chunks.Add(new HexFile.HexChunk(0, programm));
                try
                {
                    Console.WriteLine("Writing new bootloader");
                    DateTime now = DateTime.Now;
                    ldr.WriteFlash(programm, 0);
                    int ellapsed = (int)(DateTime.Now - now).TotalMilliseconds;
                    Console.WriteLine("Done in {0} ms, begin update", ellapsed);
                    ldr.LeaveBootloader();
                    Thread.Sleep(5000);
                    ldr = Loader.TryGetLoader(40);
                    Console.WriteLine("Erasing empty space");
                    ldr.EraseFlash();
                    Console.WriteLine("Success");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                return;
            }
            else if (args.Length == 2 && args[0] == "read")
            {
                byte[] programm = new byte[Loader.LOADERSTART];
                for (int i = 0; i < programm.Length; i++)
                {
                    programm[i] = 0xff;
                }
                try
                {
                    DateTime now = DateTime.Now;
                    ldr.ReadFlash(programm, 0);
                    HexFile hf = new HexFile();
                    hf.Chunks.Add(new HexFile.HexChunk(0, programm));
                    hf.Write(args[1]);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return;
                }
                return;
            }
            else if (args.Length == 2 && args[0] == "erase" && args[1] == "flash")
            {
                ldr.EraseFlash();
                return;
            }
            else if (args.Length == 2 && args[0] == "erase" && args[1] == "eeprom")
            {
                ldr.EraseEeprom();
                return;
            }
            Console.WriteLine("USE: TinyHidLoader.exe FILE.HEX - to write flash and exit to application");
            Console.WriteLine("USE: TinyHidLoader.exe FILE.HEX noleave - to write flash");
            Console.WriteLine("USE: TinyHidLoader.exe read FILE.HEX - to read flash");
            Console.WriteLine("USE: TinyHidLoader.exe erase flash - to erase flash");
            Console.WriteLine("USE: TinyHidLoader.exe erase eeprom - to erase eeprom");
        }
コード例 #15
0
ファイル: COutput.cs プロジェクト: jncronin/tysila
        private static void EmitType(TypeSpec tdr, Stream hmsw, Stream cmsw,
                                     List <string> advance_defines, List <string> external_defines, List <string> header_funcs, Target ass)
        {
            //Layout l = Layout.GetTypeInfoLayout(new Assembler.TypeToCompile { _ass = ass, tsig = new Signature.Param(tdr, ass), type = tdr }, ass, false);
            //Layout l = tdr.GetLayout(new Signature.Param(new Token(tdr), ass).Type, ass, null);

            var tname = tdr.m.GetStringEntry(MetadataStream.tid_TypeDef,
                                             tdr.tdrow, 1);
            var tns = tdr.m.GetStringEntry(MetadataStream.tid_TypeDef,
                                           tdr.tdrow, 2);

            int next_rsvd = 0;

            int align = libtysila5.layout.Layout.GetTypeAlignment(tdr, ass, false);

            if (!tdr.IsEnum)
            {
                HexFile.writeStr(hmsw, "struct " + tns + "_" + tname + " {");
                advance_defines.Add("struct " + tns + "_" + tname + ";");

                List <TypeSpec> fields = new List <TypeSpec>();
                List <string>   fnames = new List <string>();
                libtysila5.layout.Layout.GetFieldOffset(tdr, null, ass, out var is_tls, false,
                                                        fields, fnames);

                for (int i = 0; i < fields.Count; i++)
                {
                    int bytesize;
                    HexFile.writeStr(hmsw, "    " + ass.GetCType(fields[i], out bytesize) + " " + fnames[i] + ";");

                    // Pad out to align size
                    bytesize = align - bytesize;
                    while ((bytesize % 2) != 0)
                    {
                        HexFile.writeStr(hmsw, "    uint8_t __reserved" + (next_rsvd++).ToString() + ";");
                        bytesize--;
                    }
                    while ((bytesize % 4) != 0)
                    {
                        HexFile.writeStr(hmsw, "    uint16_t __reserved" + (next_rsvd++).ToString() + ";");
                        bytesize -= 2;
                    }
                    while (bytesize != 0)
                    {
                        HexFile.writeStr(hmsw, "    uint32_t __reserved" + (next_rsvd++).ToString() + ";");
                        bytesize -= 4;
                    }
                }


                //if (packed_structs)
                //    HexFile.writeStr(hmsw, "} __attribute__((__packed__));");
                //else
                HexFile.writeStr(hmsw, "};");
            }
            else
            {
                // Identify underlying type
                var  utype       = tdr.UnderlyingType;
                bool needs_comma = false;
                HexFile.writeStr(hmsw, "enum " + tns + "_" + tname + " {");

                var first_fdef = tdr.m.GetIntEntry(MetadataStream.tid_TypeDef,
                                                   tdr.tdrow, 4);
                var last_fdef = tdr.m.GetLastFieldDef(tdr.tdrow);

                for (uint fdef_row = first_fdef; fdef_row < last_fdef; fdef_row++)
                {
                    // Ensure field is static
                    var flags = tdr.m.GetIntEntry(MetadataStream.tid_Field,
                                                  (int)fdef_row, 0);
                    if ((flags & 0x10) == 0x10)
                    {
                        for (int cridx = 1; cridx <= tdr.m.table_rows[MetadataStream.tid_Constant]; cridx++)
                        {
                            int crpar_tid, crpar_row;
                            tdr.m.GetCodedIndexEntry(MetadataStream.tid_Constant,
                                                     cridx, 1, tdr.m.HasConstant, out crpar_tid, out crpar_row);

                            if (crpar_tid == MetadataStream.tid_Field &&
                                crpar_row == fdef_row)
                            {
                                var value = (int)tdr.m.GetIntEntry(MetadataStream.tid_Constant,
                                                                   cridx, 2);

                                if (tdr.m.SigReadUSCompressed(ref value) != 4)
                                {
                                    throw new NotSupportedException("Constant value not int32");
                                }

                                var v     = tdr.m.sh_blob.di.ReadInt(value);
                                var fname = tdr.m.GetStringEntry(MetadataStream.tid_Field,
                                                                 (int)fdef_row, 1);

                                if (needs_comma)
                                {
                                    HexFile.writeStr(hmsw, ",");
                                }
                                HexFile.writeStr(hmsw, "    " + fname + " = " + v.ToString(), true);
                                needs_comma = true;
                            }
                        }
                    }
                }
                HexFile.writeStr(hmsw);
                HexFile.writeStr(hmsw, "};");
            }

            HexFile.writeStr(hmsw);

            //if (output_cinit != null)
            //{
            if (!tdr.IsValueType)
            {
                string init_func = "void Init_" + tns + "_" + tname + "(struct " +
                                   tns + "_" + tname + " *obj)";
                HexFile.writeStr(cmsw, init_func);
                header_funcs.Add(init_func + ";");
                HexFile.writeStr(cmsw, "{");

                HexFile.writeStr(cmsw, "    obj->__vtbl = Get_Symbol_Addr(\"" + tdr.MangleType() + "\");");
                HexFile.writeStr(cmsw, "    obj->__mutex_lock = 0;");

                HexFile.writeStr(cmsw, "}");
                HexFile.writeStr(cmsw);

                if (tdr.Equals(tdr.m.SystemString))
                {
                    EmitStringInit(tdr, hmsw, cmsw, advance_defines, external_defines, header_funcs, ass);
                }
            }
            //}
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: Cougar/HomeAutomation
    static bool sNodeid = false; //true when a nodeid has been parsed

    #endregion Fields

    #region Methods

    static void Main(string[] args)
    {
        bool error = false;
        if (args.Length < 4) {
            //if to few arguments then print info and quit
            printSyntax();
            error = true;
        }

        if (!error) {
            //parse commandline arguments
            CommandLine=new Arguments(args);

            //check single arguments
            if (CommandLine["b"] == "true") { aBios = true; }
            if (CommandLine["r"] == "true") { aReset = true; }
            if (CommandLine["s"] == "true") { aStart = true; }
            if (CommandLine["t"] == "true") { aTerminal = true; }

            //check hexfile argument
            hexfile = CommandLine["f"];
            if (hexfile != null) {
                sHexfile = true;
            }
            if (!aTerminal && !sHexfile && !aReset && !aStart) {
                if (DEBUG_LEVEL>0) { Console.WriteLine("When not in terminal mode a hexfile, a reset or a start parameter must be supplied, I quit"); }
                error = true;
            }

            //check nodeid argument
            string node = CommandLine["n"];
            if (node != null) {
                if (!parseNodeId(node)) {
                    error = true;
                }
            }
            if (!aTerminal && !sNodeid) {
                if (DEBUG_LEVEL>0) { Console.WriteLine("When not in terminal mode a nodeid must be supplied, I quit"); }
                error = true;
            }

            //check host and port arguments
            host = CommandLine["h"];
            string sPort = CommandLine["p"];
            if ((host == null) || (sPort.Length == 0)) {
                if (DEBUG_LEVEL>0) { printSyntax(); }
                error = true;
            } else {
                try {
                    port = int.Parse(sPort);
                } catch {
                    if (DEBUG_LEVEL>0) { Console.WriteLine("Was not able to parse port, I quit"); }
                    error = true;
                }
            }
        }

        if  (!error) {
            //commandline feedback output
            if (DEBUG_LEVEL>2) {
                Console.WriteLine("canDude settings:");
                if (sNodeid) { Console.WriteLine("Nodeaddress: 0x" + String.Format("{0:x2}", nodeid)); }
                Console.WriteLine("Host: {0}:{1}", host, port);
                if (hexfile != null) { Console.WriteLine("Hexfile: {0}", hexfile); }
                Console.Write("Parameters: ");
                if (aBios) { Console.Write("Bios "); }
                if (aReset) { Console.Write("Reset "); }
                if (aStart) { Console.Write("Start "); }
                if (aTerminal) { Console.Write("Terminal"); }
                Console.WriteLine("");
            }
        }

        if (!error) {
            //connect to candaemon
            dc = new DaemonConnection();
            if (dc.init(host, port)) {
                if (DEBUG_LEVEL>1) { Console.WriteLine("Connected to candaemon"); }
            } else {
                if (DEBUG_LEVEL>0) { Console.WriteLine("Connection to candaemon could not be established, I quit"); }
                error = true;
            }
        }

        if (!error && aTerminal) {
            //terminal mode (==interactive mode)
            bool success = true;
            //load hexfile if one has been specified as commandline argument
            hf = new HexFile();
            if (sHexfile && success) {
                if (hf.loadHex(hexfile)) {
                    if (DEBUG_LEVEL>1) { Console.WriteLine("Hexfile loaded"); }
                } else { success = false; }
            }

            if (success) {
                if (DEBUG_LEVEL>1) {
                    Console.WriteLine("");
                    printHelp();		//print available commands
                    Console.WriteLine("");
                }

                string instr;
                do {
                    Console.Write("> ");			//a command has been executed, print a new console char
                    instr = Console.ReadLine();		//read std in
                } while (parseInput(instr));		//parse a line from std in

                //exit command
            }
        }

        if (!error && !aTerminal) {
            //not terminal mode
            bool success = true;

            if (sHexfile) {
                //load hexfile (a hexfile must be supplied as commandline argument)
                hf = new HexFile();
                if (hf.loadHex(hexfile)) {
                    if (DEBUG_LEVEL>1) { Console.WriteLine("Hexfile loaded"); }
                } else {
                    success = false;
                    if (DEBUG_LEVEL>0) { Console.WriteLine("Hexfile could not be loaded, I quit"); }
                }
            }

            //if a hexfile is loaded then start autodownloading sequence
            if (success) {
                bool autosuccess = true;

                CanNMT cpn = new CanNMT();
                if (aReset) {
                    //send a reset command (and wait for feedback)
                    if (!cpn.doReset(dc, nodeid)) {
                        if (DEBUG_LEVEL>0) { Console.WriteLine("Target node did not respond to reset, I quit"); }
                        autosuccess = false;
                    }
                }

                if (sHexfile && autosuccess) {
                    //send application
                    dl = new Downloader(hf, dc, nodeid, aBios);
                    if (!dl.go()) {
                        if (DEBUG_LEVEL>0) { Console.WriteLine("Error occured during download"); }
                        autosuccess = false;
                    }
                }

                if (autosuccess && aStart) {
                    //start application
                    cpn.doStart(dc, nodeid);
                }

            }
        }
        if (dc != null) {
            //stop tcp client thread
            dc.stop();
        }
    }
コード例 #17
0
ファイル: MainForm.cs プロジェクト: NSDN/NSSTC
        private void BtnWrite_Click(object sender, EventArgs e)
        {
            if (!serialPort.IsOpen)
            {
                btnConnect.Focus();
                return;
            }

            DisableAllControls();
            int size = GetChipSize();

            try
            {
                string path = boxPath.Text;
                if (path.EndsWith("hex"))
                {
                    HexFile hexFile = new HexFile(File.ReadAllLines(path));

                    if (!hexFile.Check())
                    {
                        MessageBox.Show(
                            "HEX文件校验失败",
                            "文件错误", MessageBoxButtons.OK, MessageBoxIcon.Error
                            );
                        EnableAllControls();
                        return;
                    }

                    int sumBytes = 0;
                    foreach (HexFile.HexCmd cmd in hexFile.cmds)
                    {
                        sumBytes += cmd.len;
                        if (cmd.addr + cmd.len > size)
                        {
                            MessageBox.Show(
                                "地址: " + cmd.addr.ToString("X4") + "\n" + "长度: " + cmd.len.ToString("X4"),
                                "文件过大", MessageBoxButtons.OK, MessageBoxIcon.Error
                                );
                            EnableAllControls();
                            return;
                        }
                    }

                    proBar.Maximum = sumBytes;
                    proBar.Value   = 0;

                    byte fill = listFill.SelectedIndex == 1 ? (byte)0xFF : (byte)0x00;
                    byte cod, req;
                    if (fill == 0xFF)
                    {
                        cod = 0xBF; req = 0xFB;
                    }
                    else
                    {
                        cod = 0xB0; req = 0x0B;
                    }

                    serialPort.ReadExisting();
                    SendBytes(cod);

                    bool flag = false; byte tmp = 0x00;
                    void recEvent(object obj, SerialDataReceivedEventArgs args)
                    {
                        flag = true;
                        tmp  = (byte)serialPort.ReadByte();
                    }
                    serialPort.DataReceived += recEvent;

                    proBar.Style = ProgressBarStyle.Marquee;
                    int start = Environment.TickCount;
                    while (!flag)
                    {
                        Application.DoEvents();
                        if (Environment.TickCount - start > 30 * 1000)
                        {
                            break;
                        }
                    }
                    proBar.Style             = ProgressBarStyle.Continuous;
                    serialPort.DataReceived -= recEvent;
                    if (tmp != req)
                    {
                        MessageBox.Show("芯片擦除超时或擦除指令执行失败", "芯片擦除出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        EnableAllControls();
                        return;
                    }

                    foreach (HexFile.HexCmd cmd in hexFile.cmds)
                    {
                        SendBytes(0xC0 | ((cmd.addr & 0x000F) >> 0));
                        SendBytes(0xD0 | ((cmd.addr & 0x00F0) >> 4));
                        SendBytes(0xE0 | ((cmd.addr & 0x0F00) >> 8));
                        SendBytes(0xF0 | ((cmd.addr & 0xF000) >> 12));
                        for (int i = 0; i < cmd.bytes.Length; i++)
                        {
                            SendBytes(0x80 | (cmd.bytes[i] & 0x0F), 0x90 | ((cmd.bytes[i] & 0xF0) >> 4));
                            if (checkHigh.Checked)
                            {
                                SendBytes(0xA0);
                            }
                            else
                            {
                                byte b = SendAndReadByte(0xA0);
                                if (b != cmd.bytes[i])
                                {
                                    break;
                                }
                            }
                            proBar.Value += 1;
                            Application.DoEvents();
                        }
                    }
                }
                else
                {
                    byte[] bytes    = File.ReadAllBytes(boxPath.Text);
                    int    fileSize = int.Parse(boxSize.Text, NumberStyles.HexNumber);
                    if (size < fileSize)
                    {
                        MessageBox.Show(
                            "芯片容量: " + size.ToString("X4") + "\n" + "文件大小: " + fileSize.ToString("X4"),
                            "文件过大", MessageBoxButtons.OK, MessageBoxIcon.Error
                            );
                        EnableAllControls();
                        return;
                    }
                    proBar.Maximum = fileSize;
                    proBar.Value   = 0;
                    SendBytes(0xC0, 0xD0, 0xE0, 0xF0);
                    for (int i = 0; i < fileSize; i++)
                    {
                        SendBytes(0x80 | (bytes[i] & 0x0F), 0x90 | ((bytes[i] & 0xF0) >> 4));
                        if (checkHigh.Checked)
                        {
                            SendBytes(0xA0);
                        }
                        else
                        {
                            byte b = SendAndReadByte(0xA0);
                            if (b != bytes[i])
                            {
                                break;
                            }
                        }
                        proBar.Value += 1;
                        Application.DoEvents();
                    }
                }
                if (proBar.Value == proBar.Maximum)
                {
                    MessageBox.Show("共写入: " + proBar.Value.ToString("X4"), "芯片写入结束", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("已写入: " + proBar.Value.ToString("X4"), "芯片写入中断", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "读写操作错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            EnableAllControls();
        }
コード例 #18
0
        public void OpenEeprom(string filePath)
        {
            var hexFile = HexFile.Load(filePath);

            EepromHexBoard = HexBoard.From(hexFile);
        }
コード例 #19
0
        public void OpenFlash(string filePath)
        {
            var hexFile = HexFile.Load(filePath);

            FlashHexBoard = HexBoard.From(hexFile);
        }
コード例 #20
0
ファイル: COutput.cs プロジェクト: jncronin/tysila
        internal static void WriteHeader(MetadataStream m, Target ass, string output_header,
                                         string output_cinit)
        {
            FileStream fs = new FileStream(output_header, FileMode.Create, FileAccess.Write);
            var        sw = fs;

            var hmsw = new MemoryStream();
            var cmsw = new MemoryStream();

            FileStream oci = null;

            System.IO.FileInfo header_fi = new FileInfo(output_header);
            if (output_cinit != null)
            {
                oci = new FileStream(output_cinit, FileMode.Create, FileAccess.Write);

                HexFile.writeStr(oci, "#include \"" + header_fi.Name + "\"", true);
                HexFile.writeStr(oci, "#include <string.h>", true);
                HexFile.writeStr(oci, "#include <stdlib.h>", true);
                HexFile.writeStr(oci, "#include <stdint.h>", true);
                HexFile.writeStr(oci, "#include <stddef.h>", true);
                HexFile.writeStr(oci, "", true);
                HexFile.writeStr(oci, "INTPTR Get_Symbol_Addr(const char *name);", true);
                HexFile.writeStr(oci, "", true);
            }

            List <string> advance_defines  = new List <string>();
            List <string> external_defines = new List <string>();
            List <string> func_headers     = new List <string>();

            EmitType(m.GetSimpleTypeSpec(0x1c), hmsw, cmsw, advance_defines,
                     external_defines, func_headers, ass);
            EmitType(m.GetSimpleTypeSpec(0xe), hmsw, cmsw, advance_defines,
                     external_defines, func_headers, ass);
            EmitArrayInit(hmsw, cmsw, func_headers, ass, m);

            for (int i = 1; i <= m.table_rows[MetadataStream.tid_CustomAttribute]; i++)
            {
                int type_tid, type_row;
                m.GetCodedIndexEntry(MetadataStream.tid_CustomAttribute,
                                     i, 1, m.CustomAttributeType, out type_tid,
                                     out type_row);

                MethodSpec ca_ms;
                m.GetMethodDefRow(type_tid, type_row, out ca_ms);
                var ca_ms_name = ca_ms.MangleMethod();

                if (ca_ms_name == "_ZN14libsupcs#2Edll8libsupcs22OutputCHeaderAttribute_7#2Ector_Rv_P1u1t")
                {
                    int parent_tid, parent_row;
                    m.GetCodedIndexEntry(MetadataStream.tid_CustomAttribute,
                                         i, 0, m.HasCustomAttribute, out parent_tid,
                                         out parent_row);

                    if (parent_tid == MetadataStream.tid_TypeDef)
                    {
                        var ts = m.GetTypeSpec(parent_tid, parent_row);

                        EmitType(ts, hmsw, cmsw, advance_defines,
                                 external_defines, func_headers, ass);
                    }
                }
            }

            HexFile.writeStr(sw, "");
            HexFile.writeStr(sw, "#include <stdint.h>");
            HexFile.writeStr(sw, "");
            HexFile.writeStr(sw, "#ifdef INTPTR");
            HexFile.writeStr(sw, "#undef INTPTR");
            HexFile.writeStr(sw, "#endif");
            HexFile.writeStr(sw, "#ifdef UINTPTR");
            HexFile.writeStr(sw, "#undef UINTPTR");
            HexFile.writeStr(sw, "#endif");
            HexFile.writeStr(sw, "");
            HexFile.writeStr(sw, "#define INTPTR " + ((ass.GetPointerSize() == 4) ? ass.GetCType(m.SystemInt32) : ass.GetCType(m.SystemInt64)));
            HexFile.writeStr(sw, "#define UINTPTR " + ((ass.GetPointerSize() == 4) ? ass.GetCType(m.GetSimpleTypeSpec(0x09)) : ass.GetCType(m.GetSimpleTypeSpec(0x0b))));
            HexFile.writeStr(sw, "");
            EmitArrayType(sw, ass, m);
            foreach (string s in advance_defines)
            {
                HexFile.writeStr(sw, s);
            }
            HexFile.writeStr(sw, "");
            if (oci != null)
            {
                foreach (string s2 in func_headers)
                {
                    HexFile.writeStr(sw, s2);
                }
                HexFile.writeStr(sw, "");
            }
            hmsw.Flush();
            StreamReader hmsr = new StreamReader(hmsw);

            hmsr.BaseStream.Seek(0, SeekOrigin.Begin);
            string hs = hmsr.ReadLine();

            while (hs != null)
            {
                HexFile.writeStr(sw, hs);
                hs = hmsr.ReadLine();
            }

            sw.Close();

            if (oci != null)
            {
                foreach (string s in external_defines)
                {
                    HexFile.writeStr(oci, s);
                }
                HexFile.writeStr(oci, "");

                cmsw.Flush();
                StreamReader cmsr = new StreamReader(cmsw);
                cmsr.BaseStream.Seek(0, SeekOrigin.Begin);
                string cs = cmsr.ReadLine();
                while (cs != null)
                {
                    HexFile.writeStr(oci, cs);
                    cs = cmsr.ReadLine();
                }
                oci.Close();
            }
        }
コード例 #21
0
ファイル: HexFileIO.cs プロジェクト: GuochuSang/-
        public HexFile ReadHexFile(string path)
        {
            HexFile hexFile = new HexFile();

            return(hexFile);
        }
コード例 #22
0
        // return true if the CPU was reset and the program was loaded
        public bool ResetCPU(string kernelFilename)
        {
            if (CPU != null)
            {
                CPU.DebugPause = true;
                //CPU.Halt();
            }

            if (kernelFilename != null)
            {
                LoadedKernel = kernelFilename;
            }

            // If the reset vector is not set in Bank 0, but it is set in Bank 18, the copy bank 18 into bank 0.
            int BasePageAddress = 0x18_0000;

            if (boardVersion == BoardVersion.RevC)
            {
                BasePageAddress = 0x38_0000;
            }

            if (LoadedKernel.EndsWith(".fnxml", true, null))
            {
                this.ResetMemory();
                FoeniXmlFile fnxml = new FoeniXmlFile(this, Resources);
                fnxml.Load(LoadedKernel);
                boardVersion = fnxml.Version;
            }
            else
            {
                LoadedKernel = HexFile.Load(MemMgr.RAM, LoadedKernel, BasePageAddress, out _, out _);
                if (LoadedKernel != null)
                {
                    if (lstFile == null)
                    {
                        lstFile = new ListFile(LoadedKernel);
                    }
                    else
                    {
                        // TODO: This results in lines of code to be shown in incorrect order - Fix
                        ListFile tempList = new ListFile(LoadedKernel);
                        foreach (DebugLine line in tempList.Lines.Values)
                        {
                            if (lstFile.Lines.ContainsKey(line.PC))
                            {
                                lstFile.Lines.Remove(line.PC);
                            }
                            lstFile.Lines.Add(line.PC, line);
                            for (int i = 1; i < line.commandLength; i++)
                            {
                                if (lstFile.Lines.ContainsKey(line.PC + i))
                                {
                                    lstFile.Lines.Remove(line.PC + i);
                                }
                            }
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }

            // See if lines of code exist in the 0x18_0000 to 0x18_FFFF block for RevB or 0x38_0000 to 0x38_FFFF block for Rev C
            List <DebugLine> copiedLines = new List <DebugLine>();

            if (lstFile.Lines.Count > 0)
            {
                foreach (DebugLine line in lstFile.Lines.Values)
                {
                    if (line != null && line.PC >= BasePageAddress && line.PC < BasePageAddress + 0x1_0000)
                    {
                        DebugLine dl = (DebugLine)line.Clone();
                        dl.PC -= BasePageAddress;
                        copiedLines.Add(dl);
                    }
                }
            }
            if (copiedLines.Count > 0)
            {
                foreach (DebugLine line in copiedLines)
                {
                    if (lstFile.Lines.ContainsKey(line.PC))
                    {
                        lstFile.Lines.Remove(line.PC);
                    }
                    lstFile.Lines.Add(line.PC, line);
                }
            }
            CPU.Reset();
            return(true);
        }
コード例 #23
0
        private void SendBinaryButton_Click(object sender, EventArgs e)
        {
            SendBinaryButton.Enabled = false;
            DisconnectButton.Enabled = false;
            hideLabelTimer_Tick(null, null);
            int transmissionSize = GetTransmissionSize();

            UploadProgressBar.Maximum = transmissionSize;
            UploadProgressBar.Value   = 0;
            UploadProgressBar.Visible = true;

            int BaseBankAddress = 0x38_0000;

            if (boardVersion == BoardVersion.RevB)
            {
                BaseBankAddress = 0x18_0000;
            }

            if (SendFileRadio.Checked)
            {
                if (serial.IsOpen)
                {
                    // Get into Debug mode (Reset the CPU and keep it in that state and Gavin will take control of the bus)
                    if (DebugModeCheckbox.Checked)
                    {
                        GetFnxInDebugMode();
                    }

                    if (Path.GetExtension(FileNameTextBox.Text).ToUpper().Equals(".BIN"))
                    {
                        // Read the bytes and put them in the buffer
                        byte[] DataBuffer    = System.IO.File.ReadAllBytes(FileNameTextBox.Text);
                        int    FnxAddressPtr = int.Parse(C256DestAddress.Text.Replace(":", ""), System.Globalization.NumberStyles.AllowHexSpecifier);
                        Console.WriteLine("Starting Address: " + FnxAddressPtr);
                        Console.WriteLine("File Size: " + transmissionSize);
                        SendData(DataBuffer, FnxAddressPtr, transmissionSize);

                        // Update the Reset Vectors from the Binary Files Considering that the Files Keeps the Vector @ $00:FF00
                        if (FnxAddressPtr < 0xFF00 && (FnxAddressPtr + DataBuffer.Length) > 0xFFFF || (FnxAddressPtr == BaseBankAddress && DataBuffer.Length > 0xFFFF))
                        {
                            PreparePacket2Write(DataBuffer, 0x00FF00, 0x00FF00, 256);
                        }
                    }
                    else
                    {
                        bool resetVector = false;
                        // Page FF is used to store IRQ vectors - this is only used when the program modifies the
                        // values between BaseBank + FF00 to BaseBank + FFFF
                        // BaseBank on RevB is $18
                        // BaseBank on RevC is $38
                        byte[] pageFF = PreparePacket2Read(0xFF00, 0x100);
                        // If send HEX files, each time we encounter a "bank" change - record 04 - send a new data block
                        string[] lines   = System.IO.File.ReadAllLines(FileNameTextBox.Text);
                        int      bank    = 0;
                        int      address = 0;

                        foreach (string l in lines)
                        {
                            if (l.StartsWith(":"))
                            {
                                string mark     = l.Substring(0, 1);
                                string reclen   = l.Substring(1, 2);
                                string offset   = l.Substring(3, 4);
                                string rectype  = l.Substring(7, 2);
                                string data     = l.Substring(9, l.Length - 11);
                                string checksum = l.Substring(l.Length - 2);

                                switch (rectype)
                                {
                                case "00":
                                    int    length     = Convert.ToInt32(reclen, 16);
                                    byte[] DataBuffer = new byte[length];
                                    address = HexFile.GetByte(offset, 0, 2);
                                    for (int i = 0; i < data.Length; i += 2)
                                    {
                                        DataBuffer[i / 2] = (byte)HexFile.GetByte(data, i, 1);
                                    }
                                    PreparePacket2Write(DataBuffer, bank + address, 0, length);

                                    // TODO - make this backward compatible
                                    if (bank + address >= (BaseBankAddress + 0xFF00) && (bank + address) < (BaseBankAddress + 0xFFFF))
                                    {
                                        int pageFFLen = length - ((bank + address + length) - (BaseBankAddress + 0x1_0000));
                                        if (pageFFLen > length)
                                        {
                                            pageFFLen = length;
                                        }
                                        Array.Copy(DataBuffer, 0, pageFF, bank + address - (BaseBankAddress + 0xFF00), length);
                                        resetVector = true;
                                    }
                                    UploadProgressBar.Increment(length);

                                    break;

                                case "01":
                                    // Don't do anything... this is the end of file record.
                                    break;

                                case "02":
                                    bank = HexFile.GetByte(data, 0, 2) * 16;
                                    break;

                                case "04":
                                    bank = HexFile.GetByte(data, 0, 2) << 16;
                                    break;

                                default:
                                    Console.WriteLine("Unsupport HEX record type:" + rectype);
                                    break;
                                }
                            }
                        }
                        if (DebugModeCheckbox.Checked)
                        {
                            // Update the Reset Vectors from the Binary Files Considering that the Files Keeps the Vector @ $00:FF00
                            if (resetVector)
                            {
                                PreparePacket2Write(pageFF, 0x00FF00, 0, 256);
                            }
                        }
                    }
                    if (ReflashCheckbox.Checked && MessageBox.Show("Are you sure you want to reflash your C256 System?", "Reflash", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        CountdownLabel.Visible = true;
                        this.Update();

                        EraseFlash();
                        int SrcFlashAddress = Convert.ToInt32(C256DestAddress.Text.Replace(":", ""), 16);
                        ProgramFlash(SrcFlashAddress);
                        CountdownLabel.Visible = false;
                    }
                    if (DebugModeCheckbox.Checked)
                    {
                        // The Loading of the File is Done, Reset the FNX and Get out of Debug Mode
                        ExitFnxDebugMode();
                    }
                    HideProgressBarAfter5Seconds("Transfer Done! System Reset!");
                }
            }
            else if (BlockSendRadio.Checked && kernel.CPU != null)
            {
                // Get into Debug mode (Reset the CPU and keep it in that state and Gavin will take control of the bus)
                if (DebugModeCheckbox.Checked)
                {
                    GetFnxInDebugMode();
                }
                int blockAddress = Convert.ToInt32(EmuSrcAddress.Text.Replace(":", ""), 16);
                // Read the data directly from emulator memory
                int    offset        = 0;
                int    FnxAddressPtr = int.Parse(C256DestAddress.Text.Replace(":", ""), System.Globalization.NumberStyles.AllowHexSpecifier);
                byte[] DataBuffer    = new byte[transmissionSize]; // Maximum 2 MB, example from $0 to $1F:FFFF.
                for (int start = blockAddress; start < blockAddress + transmissionSize; start++)
                {
                    DataBuffer[offset++] = kernel.CPU.MemMgr.ReadByte(start);
                }
                SendData(DataBuffer, FnxAddressPtr, transmissionSize);
                // Update the Reset Vectors from the Binary Files Considering that the Files Keeps the Vector @ $00:FF00
                if (FnxAddressPtr < 0xFF00 && (FnxAddressPtr + DataBuffer.Length) > 0xFFFF || (FnxAddressPtr == BaseBankAddress && DataBuffer.Length > 0xFFFF))
                {
                    PreparePacket2Write(DataBuffer, 0x00FF00, 0x00FF00, 256);
                }
                if (DebugModeCheckbox.Checked)
                {
                    // The Loading of the File is Done, Reset the FNX and Get out of Debug Mode
                    ExitFnxDebugMode();
                }
                HideProgressBarAfter5Seconds("Transfer Done! System Reset!");
            }
            else
            {
                int    blockAddress = Convert.ToInt32(C256SrcAddress.Text.Replace(":", ""), 16);
                byte[] DataBuffer   = new byte[transmissionSize]; // Maximum 2 MB, example from $0 to $1F:FFFF.
                if (FetchData(DataBuffer, blockAddress, transmissionSize, DebugModeCheckbox.Checked))
                {
                    MemoryRAM mem = new MemoryRAM(blockAddress, transmissionSize);
                    mem.Load(DataBuffer, 0, 0, transmissionSize);
                    MemoryWindow tempMem = new MemoryWindow
                    {
                        Memory = mem,
                        Text   = "C256 Memory from " + blockAddress.ToString("X6") +
                                 " to " + (blockAddress + transmissionSize - 1).ToString("X6")
                    };
                    tempMem.GotoAddress(blockAddress);
                    tempMem.AllowSave();
                    tempMem.Show();
                }
                SendBinaryButton.Enabled = true;
                DisconnectButton.Enabled = true;
            }
        }
コード例 #24
0
        private void SendBinaryButton_Click(object sender, EventArgs e)
        {
            SendBinaryButton.Enabled = false;
            DisconnectButton.Enabled = false;

            int transmissionSize = GetTransmissionSize();

            UploadProgressBar.Maximum = transmissionSize;
            UploadProgressBar.Value   = 0;
            UploadProgressBar.Visible = true;

            if (SendFileRadio.Checked)
            {
                if (Path.GetExtension(FileNameTextBox.Text).ToUpper().Equals(".BIN"))
                {
                    //byte[] DataBuffer = new byte[transmissionSize];  // Maximum 2 MB, example from $0 to $1F:FFFF.
                    // Read the bytes and put them in the buffer
                    byte[] DataBuffer    = System.IO.File.ReadAllBytes(FileNameTextBox.Text);
                    int    FnxAddressPtr = int.Parse(C256DestAddress.Text.Replace(":", ""), System.Globalization.NumberStyles.AllowHexSpecifier);
                    Console.WriteLine("Starting Address: " + FnxAddressPtr);
                    Console.WriteLine("Size of File: " + transmissionSize);
                    SendData(DataBuffer, FnxAddressPtr, transmissionSize, DebugModeCheckbox.Checked);
                }
                else
                {
                    if (serial.IsOpen)
                    {
                        // Get into Debug mode (Reset the CPU and keep it in that state and Gavin will take control of the bus)
                        if (DebugModeCheckbox.Checked)
                        {
                            GetFnxInDebugMode();
                        }

                        // If send HEX files, each time we encounter a "bank" change - record 04 - send a new data block
                        string[] lines       = System.IO.File.ReadAllLines(FileNameTextBox.Text);
                        int      bank        = 0;
                        int      address     = 0;
                        byte[]   pageFF      = new byte[256];
                        bool     resetVector = false;
                        foreach (string l in lines)
                        {
                            if (l.StartsWith(":"))
                            {
                                string mark     = l.Substring(0, 1);
                                string reclen   = l.Substring(1, 2);
                                string offset   = l.Substring(3, 4);
                                string rectype  = l.Substring(7, 2);
                                string data     = l.Substring(9, l.Length - 11);
                                string checksum = l.Substring(l.Length - 2);

                                switch (rectype)
                                {
                                case "00":
                                    int    length     = Convert.ToInt32(reclen, 16);
                                    byte[] DataBuffer = new byte[length];
                                    address = HexFile.GetByte(offset, 0, 2);
                                    for (int i = 0; i < data.Length; i += 2)
                                    {
                                        DataBuffer[i / 2] = (byte)HexFile.GetByte(data, i, 1);
                                    }
                                    PreparePacket2Write(DataBuffer, bank + address, 0, length);
                                    if (bank + address >= 0xFF00 && (bank + address) < 0xFFFF)
                                    {
                                        int pageFFLen = length - ((bank + address + length) - 0x1_0000);
                                        if (pageFFLen > length)
                                        {
                                            pageFFLen = length;
                                        }
                                        Array.Copy(DataBuffer, 0, pageFF, bank + address - 0xFF00, pageFFLen);
                                        resetVector = true;
                                    }
                                    else if (bank + address >= 0x18_FF00 && (bank + address) < 0x18_FFFF)
                                    {
                                        int pageFFLen = length - ((bank + address + length) - 0x19_0000);
                                        if (pageFFLen > length)
                                        {
                                            pageFFLen = length;
                                        }
                                        Array.Copy(DataBuffer, 0, pageFF, bank + address - 0x18_FF00, length);
                                        resetVector = true;
                                    }
                                    UploadProgressBar.Increment(length);

                                    break;

                                case "04":
                                    bank = HexFile.GetByte(data, 0, 2) << 16;
                                    break;
                                }
                            }
                        }

                        if (DebugModeCheckbox.Checked)
                        {
                            // Update the Reset Vectors from the Binary Files Considering that the Files Keeps the Vector @ $00:FF00
                            if (resetVector)
                            {
                                PreparePacket2Write(pageFF, 0x00FF00, 0, 256);
                            }
                            // The Loading of the File is Done, Reset the FNX and Get out of Debug Mode
                            ExitFnxDebugMode();
                        }
                        MessageBox.Show("Transfer Done! System Reset!", "Send Binary Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            else if (BlockSendRadio.Checked)
            {
                int blockAddress = Convert.ToInt32(EmuSrcAddress.Text.Replace(":", ""), 16);
                // Read the data directly from emulator memory
                int    offset        = 0;
                int    FnxAddressPtr = int.Parse(C256DestAddress.Text.Replace(":", ""), System.Globalization.NumberStyles.AllowHexSpecifier);
                byte[] DataBuffer    = new byte[transmissionSize]; // Maximum 2 MB, example from $0 to $1F:FFFF.
                for (int start = blockAddress; start < blockAddress + transmissionSize; start++)
                {
                    DataBuffer[offset++] = Memory.ReadByte(start);
                }
                SendData(DataBuffer, FnxAddressPtr, transmissionSize, DebugModeCheckbox.Checked);
            }
            else
            {
                int    blockAddress = Convert.ToInt32(C256SrcAddress.Text.Replace(":", ""), 16);
                byte[] DataBuffer   = new byte[transmissionSize]; // Maximum 2 MB, example from $0 to $1F:FFFF.
                if (FetchData(DataBuffer, blockAddress, transmissionSize, DebugModeCheckbox.Checked))
                {
                    BasicMemory mem = new BasicMemory("tempbuffer", blockAddress, transmissionSize);
                    mem.Load(DataBuffer, 0, 0, transmissionSize);
                    MemoryWindow tempMem = new MemoryWindow
                    {
                        Memory = mem,
                        Text   = "C256 Memory from " + blockAddress.ToString("X6") +
                                 " to " + (blockAddress + transmissionSize - 1).ToString("X6")
                    };
                    tempMem.GotoAddress(blockAddress);
                    tempMem.Show();
                }
            }

            UploadProgressBar.Visible = false;
            SendBinaryButton.Enabled  = true;
            DisconnectButton.Enabled  = true;
        }