/// <summary> /// Function added to display result of cpu exercizer test /// </summary> public void PerformMultipleStep(string fullPath, int memoryOffset) { if (MCU.LoadFileInMemoryAt(fullPath, memoryOffset)) { _currentState = TCurrentState.RUNNING; while (_currentState != TCurrentState.STOPPED) { if (!_cpu.Halted) { _cpu.Fetch(); _cpu.Execute(); } // CP/M warm boot (test finished and restarted itself) if (_cpu.PC == 0x00) { _currentState = TCurrentState.STOPPED; } // Call to CP/M bios emulated function to write characters on screen if (_cpu.PC == 0x05) { _cpu.PerformBdosCall(); } } } }
public Status SetMCU(MCU _mcu) { if (mode == Mode.USB_HID && (mcu != MCU.MSP430_F5xx && mcu != MCU.MSP430_F543x_A && mcu != MCU.MSP430_F543x_NON_A && mcu != MCU.MSP430_F6xx)) { return(Utils.StatusCreate(216)); } mcu = _mcu; if (mode == Mode.USB_HID) { protocol = Protocol.USB_5_6; } else { if (_mcu == MCU.MSP430_F1xx || _mcu == MCU.MSP430_F2xx || _mcu == MCU.MSP430_F4xx || _mcu == MCU.MSP430_G2xx3) { protocol = Protocol.UART_1_2_4; } else { protocol = Protocol.UART_5_6; } } return(Utils.StatusCreate(0)); }
public MCUDefinitionFromProject GenerateMCUDefinitionFromProject(ReconfigurableProjectImportParameters parameters, IProjectImportService service) { var gpdscFile = Path.ChangeExtension(parameters.ProjectFile, ".gpdsc"); var parsedProject = ParseProjectFile(gpdscFile, true); string baseDir = Path.GetFullPath(Path.GetDirectoryName(parameters.ProjectFile)); var mcu = new MCU { ID = parsedProject.DeviceName, AdditionalSourceFiles = parsedProject.AllFiles.Where(f => f.EndsWith(".h", StringComparison.InvariantCultureIgnoreCase)).Select(f => MakeBSPPath(f, baseDir)).ToArray(), AdditionalHeaderFiles = parsedProject.AllFiles.Where(f => !f.EndsWith(".h", StringComparison.InvariantCultureIgnoreCase)).Select(f => MakeBSPPath(f, baseDir)).ToArray(), CompilationFlags = new ToolFlags { IncludeDirectories = parsedProject.IncludeDirectories.Select(d => MakeBSPPath(d, baseDir)).ToArray(), PreprocessorMacros = parsedProject.PreprocessorMacros.ToArray(), COMMONFLAGS = parsedProject.CFLAGS, LinkerScript = MakeBSPPath(parsedProject.LinkerScript, baseDir), } }; return(new MCUDefinitionFromProject { MCU = mcu, VirtualFolderStructure = parsedProject.RootDirectory, }); }
static void CompareField(MCU m1, MCU m2, string fieldName) { object o1 = typeof(MCU).GetField(fieldName).GetValue(m1); object o2 = typeof(MCU).GetField(fieldName).GetValue(m2); if (!o1.Equals(o2)) { Console.WriteLine($"Mismatching {fieldName} for {m1.ID}: {o1:x} => {o2:x}"); } }
public void Run(string[] multipleRomFiles) { if (_currentState == TCurrentState.STOPPED) { if (MCU.LoadMultipleFiles(multipleRomFiles)) { _stopWatch.Start(); _currentState = TCurrentState.RUNNING; _timer = new Timer(TimerAsync_CallBack, null, 0, Timeout.Infinite); } } }
public void Run(String fullPath, int offset) { if (_currentState == TCurrentState.STOPPED) { if (MCU.LoadFileInMemoryAt(fullPath, offset)) { _stopWatch.Start(); _currentState = TCurrentState.RUNNING; _timer = new Timer(TimerAsync_CallBack, null, 0, Timeout.Infinite); } } }
public void DetectAndApplyMemorySizes(MCU mcu, string linkerScript) { Console.Write("."); linkerScript = _LinkerScriptCache.ProvidePreprocessedLinkerScript(linkerScript, 0); string tmpFile = Path.GetTempPath() + "LinkerScriptQuery.c"; File.WriteAllText(tmpFile, ""); string mapFile = Path.ChangeExtension(tmpFile, ".map"); var proc = Process.Start(new ProcessStartInfo(Path.Combine(toolchainDir, @"bin\arm-eabi-gcc.exe"), $"-T {linkerScript} {tmpFile} -Wl,-Map,{mapFile} -Wl,--defsym,__Vectors=0 -Wl,--defsym,Stack_Size=0") { UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, }); proc.WaitForExit(); var rgMemory = new Regex("^([^ \t]+)[ \t]+0x([0-9a-fA-F]+)[ \t]+0x([0-9a-fA-F]+)"); var memories = File.ReadAllLines(mapFile) .SkipWhile(l => !l.Contains("Memory Configuration")) .TakeWhile(l => !l.Contains("Linker script and memory map")) .Select(l => rgMemory.Match(l)) .Where(m => m.Success) .Select(m => new MCUMemory { Name = m.Groups[1].Value, Address = uint.Parse(m.Groups[2].Value, System.Globalization.NumberStyles.AllowHexSpecifier), Size = uint.Parse(m.Groups[3].Value, System.Globalization.NumberStyles.AllowHexSpecifier) }) .Where(m => m.Name != "*default*") .ToArray(); mcu.MemoryMap = new AdvancedMemoryMap { Memories = memories }; var flash = memories.FirstOrDefault(m => m.Name.ToUpper() == "FLASH" || m.Name == "m_text" || m.Name == "ROM" || m.Name == "rom" || m.Name == "MFlash256"); var ram = memories.First(m => m.Name.ToUpper() == "RAM" || m.Name == "m_data" || m.Name == "RAM_INTERN" || m.Name == "SRAM1" || m.Name == "RAM0" || m.Name.StartsWith("Ram0_") || m.Name.StartsWith("DSRAM_")); if (flash == null) { if (mcu.ID != "LPC4330_M4" && mcu.ID != "LPC4337" && mcu.ID != "LPC4330_M0") { throw new Exception("Could not locate FLASH memory"); } } else { mcu.FLASHSize = (int)flash.Size; mcu.FLASHBase = (uint)flash.Address; } mcu.RAMSize = (int)ram.Size; mcu.RAMBase = (uint)ram.Address; }
private static void FixGPDSCErrors(BoardSupportPackage bsp, MCU mcu, string extractedProjectDirectory, FlagsFromMakefile flagsFromMakefile, string relativeFLASHScript) { //1. Startup files may not be referenced in the GPDSC file string[] startupFiles = Directory.GetFiles(Path.Combine(extractedProjectDirectory, Path.GetDirectoryName(relativeFLASHScript)), "*.c") .Select(f => "$$SYS:BSP_ROOT$$/" + f.Substring(extractedProjectDirectory.Length).TrimStart('\\').Replace('\\', '/')) .Except(bsp.Frameworks.SelectMany(fw => fw.AdditionalSourceFiles)) .ToArray(); //2. Some include directories are not referenced in the GPDSC file string[] extraIncludeDirs = flagsFromMakefile.RelativeIncludeDirs .Select(d => "$$SYS:BSP_ROOT$$/" + d) .Except(bsp.Frameworks.SelectMany(fw => fw.AdditionalIncludeDirs)) .ToArray(); mcu.AdditionalSourceFiles = startupFiles; mcu.CompilationFlags = mcu.CompilationFlags.Merge(new ToolFlags { IncludeDirectories = extraIncludeDirs }); }
private Emulator() { _currentState = TCurrentState.STOPPED; _nextVblankInterrupt = GPU.END_VBLANK_OPCODE; _mcu = new MCUR(); _cpu = new CPU(); _cpu.Initialize(); _gpu = new GPU(); _gpu.Initialize(); _devices = new Devices(); _stopWatch = new Stopwatch(); _currentState = TCurrentState.STOPPED; _autoReset = new AutoResetEvent(false); }
public void StartStop() { string err = ""; if (this.ControlProcess.Password.Length != 0 && !this.ControlProcess.ValidateBslPassword(this.ControlProcess.Password.Length / 2, this.ControlProcess.MCU)) { err += $"{ERR1}\n"; } if (this.FwPath == "" || !File.Exists(this.FwPath)) { err += $"{ERR2}\n"; } if (err != "") { MessageBox.Show(err.TrimEnd('\n'), "BSL430.NET", MessageBoxButton.OK, MessageBoxImage.Warning); return; } MCU mcu = this.ControlProcess.MCU; if (this.FirstUpload && (mcu == MCU.MSP430_F1xx || mcu == MCU.MSP430_F2xx || mcu == MCU.MSP430_F4xx || mcu == MCU.MSP430_G2xx3)) { var result = MessageBox.Show("As this is your first upload, and you are targetting old 1xx/2xx/4xx protocol, you should be careful. " + "If you dont enter password, Mass Erase is executed first. This is standard procedure when targetting newer 5xx/6xx protocol. " + "However old 1xx/2xx/4xx bootloader protocols erase complete memory including Info A (with CALIBRATION data) if Mass Erase is executed " + "or incorrect password is entered, provided LOCK A bit is not set.\n\nDo you still want to continue?", "BSL430.NET", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.Yes) { this.FirstUpload = false; } else { return; } } this.ControlProcess?.StartStop(); }
public MCU[] LoadMCUList(IProjectImportService service, Dictionary <string, string> toolLocations) { var stm32cubeMXExe = toolLocations[_STM32CubeMX.ID]; var xmlFile = Path.Combine(Path.GetDirectoryName(stm32cubeMXExe), @"db\mcu\families.xml"); List <MCU> result = new List <MCU>(); var xml = new XmlDocument(); xml.Load(xmlFile); foreach (var family in xml.DocumentElement.SelectNodes("Family").OfType <XmlElement>()) { var familyName = family.GetAttribute("Name"); foreach (var subfamily in family.SelectNodes("SubFamily").OfType <XmlElement>()) { var subfamilyName = subfamily.GetAttribute("Name"); foreach (var mcu in subfamily.SelectNodes("Mcu").OfType <XmlElement>()) { var mcuName = mcu.GetAttribute("Name"); var refName = mcu.GetAttribute("RefName"); if (!string.IsNullOrEmpty(mcuName) && !string.IsNullOrEmpty(refName)) { var mcuObject = new MCU { ID = refName, //UserFriendlyName = mcuName, }; int.TryParse(mcu.SelectSingleNode("Flash")?.InnerText, out mcuObject.FLASHSize); int.TryParse(mcu.SelectSingleNode("Ram")?.InnerText, out mcuObject.RAMSize); mcuObject.FLASHSize *= 1024; mcuObject.RAMSize *= 1024; mcuObject.HierarchicalPath = $"{familyName}\\{subfamilyName}"; result.Add(mcuObject); } } } } return(result.ToArray()); }
public void StartStop() { MCU mcu = this.ControlProcess.MCU; if (this.FirstErase && (mcu == MCU.MSP430_F1xx || mcu == MCU.MSP430_F2xx || mcu == MCU.MSP430_F4xx || mcu == MCU.MSP430_G2xx3)) { var result = MessageBox.Show("As this is your first erase, and you are targetting old 1xx/2xx/4xx protocol, you should be careful. " + "Old 1xx/2xx/4xx bootloader protocols erase complete memory including Info A (with CALIBRATION data) if Mass Erase is executed, " + "provided LOCK A bit is not set.\n\nDo you still want to continue?", "BSL430.NET", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (result == MessageBoxResult.Yes) { this.FirstErase = false; } else { return; } } this.ControlProcess?.StartStop(); }
internal void CopyAndAttachRegisterDefinitions(MCU mcu) { foreach (var rule in nameRules) { var m = rule.Key.Match(mcu.ID); if (m.Success) { string devRegex = rule.Value; for (int i = 1; i < m.Groups.Count; i++) { devRegex = devRegex.Replace(@"\" + i, m.Groups[i].Value); } Regex devRegexObj = new Regex(devRegex); string definition = null; foreach (var dev in mcuDefs) { if (devRegexObj.IsMatch(dev.Key)) { definition = dev.Value; } } if (definition == null) { Console.WriteLine("\r\nWarning: cannot find device register definition for " + devRegex); } else { mcu.MCUDefinitionFile = "DeviceDefinitions/" + Path.GetFileName(definition); string targetPath = Path.Combine(mbedRoot, mcu.MCUDefinitionFile + ".gz"); Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); File.Copy(definition + ".gz", targetPath, true); } break; } } }
public MCU(string id, string desc = null, string signature = null, int flash = 0, int eeprom = 0, MCU parent = null) : base(id, desc, parent) { if (signature != null) { this.signature = signature.ToLower(); } this.flash = flash; this.eeprom = eeprom; }
static void Main(string[] args) { var generator = new MbedBSPGenerator("5.9.2"); bool skipRescan = args.Contains("/norescan"); string suffix = ""; generator.UpdateGitAndRescanTargets(skipRescan); ParsedTargetList parsedTargets = XmlTools.LoadObject <ParsedTargetList>(Path.Combine(generator.outputDir, "mbed", "ParsedTargets.xml")); generator.PatchBuggyFiles(); BoardSupportPackage bsp = new BoardSupportPackage { PackageID = "com.sysprogs.arm.mbed", PackageDescription = "ARM mbed", PackageVersion = generator.Version + suffix, GNUTargetID = "arm-eabi", GeneratedMakFileName = "mbed.mak", BSPSourceFolderName = "mbed Files" }; var validTargets = parsedTargets.Targets.Where(t => t.BaseConfiguration != null).ToArray(); MCUFamily commonFamily = new MCUFamily { ID = "MBED_CORE", AdditionalSourceFiles = generator.ConvertPaths(Intersect(validTargets.Select(t => t.BaseConfiguration.SourceFiles))), AdditionalHeaderFiles = generator.ConvertPaths(Intersect(validTargets.Select(t => t.BaseConfiguration.HeaderFiles))), SymbolsRequiredByLinkerScript = new[] { "__Vectors", "Stack_Size" }, CompilationFlags = new ToolFlags { IncludeDirectories = generator.ConvertPaths(Intersect(validTargets.Select(t => t.BaseConfiguration.IncludeDirectories))), PreprocessorMacros = Intersect(validTargets.Select(t => t.BaseConfiguration.EffectivePreprocessorMacros)) } }; bsp.MCUFamilies = new[] { commonFamily }; List <MCU> mcus = new List <MCU>(); Dictionary <string, ConditionalConfigAggregator> libraryAndFeatureConfigs = new Dictionary <string, ConditionalConfigAggregator>(); Console.WriteLine("Generating target definitions..."); foreach (var target in validTargets) { if (string.IsNullOrEmpty(target.BaseConfiguration.LinkerScript)) { Console.WriteLine($"Skipping {target.ID}: no linker script defined"); continue; } var mcu = new MCU { FamilyID = commonFamily.ID, ID = target.ID, AdditionalSourceFiles = generator.ConvertPaths(target.BaseConfiguration.SourceFiles), AdditionalHeaderFiles = generator.ConvertPaths(target.BaseConfiguration.HeaderFiles), CompilationFlags = new ToolFlags { IncludeDirectories = generator.ConvertPaths(target.BaseConfiguration.IncludeDirectories), PreprocessorMacros = target.BaseConfiguration.EffectivePreprocessorMacros, LinkerScript = generator.ConvertPaths(new[] { target.BaseConfiguration.LinkerScript })[0], COMMONFLAGS = target.CFLAGS.Replace(';', ' '), }, ConfigurableProperties = new PropertyList { PropertyGroups = new List <PropertyGroup> { new PropertyGroup { UniqueID = "com.sysprogs.mbed.", Properties = target.BaseConfiguration.EffectiveConfigurableProperties.ToList() } } } }; generator.DetectAndApplyMemorySizes(mcu, target.BaseConfiguration.LinkerScript); if (mcu.CompilationFlags.COMMONFLAGS.Contains("-mfloat-abi")) { string[] flags = mcu.CompilationFlags.COMMONFLAGS.Split(' '); string defaultValue = flags.First(f => f.StartsWith("-mfloat-abi")); var property = new PropertyEntry.Enumerated { Name = "Floating point support", UniqueID = "floatmode", SuggestionList = new PropertyEntry.Enumerated.Suggestion[] { new PropertyEntry.Enumerated.Suggestion { InternalValue = "-mfloat-abi=soft", UserFriendlyName = "Software" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "-mfloat-abi=hard", UserFriendlyName = "Hardware" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "-mfloat-abi=softfp", UserFriendlyName = "Hardware with Software interface" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "", UserFriendlyName = "Unspecified" }, }, }; property.DefaultEntryIndex = Enumerable.Range(0, property.SuggestionList.Length).First(i => property.SuggestionList[i].InternalValue == defaultValue); flags[Array.IndexOf(flags, defaultValue)] = "$$" + mcu.ConfigurableProperties.PropertyGroups[0].UniqueID + property.UniqueID + "$$"; mcu.CompilationFlags.COMMONFLAGS = string.Join(" ", flags); mcu.ConfigurableProperties.PropertyGroups[0].Properties.Add(property); } mcu.AdditionalSourceFiles = mcu.AdditionalSourceFiles.Except(commonFamily.AdditionalSourceFiles).ToArray(); mcu.AdditionalHeaderFiles = mcu.AdditionalHeaderFiles.Except(commonFamily.AdditionalHeaderFiles).ToArray(); mcu.CompilationFlags.IncludeDirectories = mcu.CompilationFlags.IncludeDirectories.Except(commonFamily.CompilationFlags.IncludeDirectories).ToArray(); mcu.CompilationFlags.PreprocessorMacros = mcu.CompilationFlags.PreprocessorMacros.Except(commonFamily.CompilationFlags.PreprocessorMacros).ToArray(); foreach (var cfg in target.DerivedConfigurations) { cfg.MergeScatteredConfigurations(); ConditionalConfigAggregator agg; if (!libraryAndFeatureConfigs.TryGetValue(cfg.CanonicalKey, out agg)) { agg = libraryAndFeatureConfigs[cfg.CanonicalKey] = new ConditionalConfigAggregator(cfg); } agg.AddedSettingsPerTargets[target.ID] = cfg.Configuration.Subtract(target.BaseConfiguration, cfg.CanonicalKey, cfg.Library != null); } if (!generator.ConvertSoftdevicesAndPatchTarget(mcu, target.BaseConfiguration.HexFiles)) { mcu.CompilationFlags.LinkerScript = generator.ConvertPath(generator.PreprocessLinkerScriptIfNeeded(mcu.CompilationFlags.LinkerScript)); } generator.CopyAndAttachRegisterDefinitions(mcu); mcus.Add(mcu); } bsp.SupportedMCUs = mcus.ToArray(); List <FileCondition> fileConditions = new List <FileCondition>(); List <ConditionalToolFlags> conditionalFlags = new List <ConditionalToolFlags>(); List <EmbeddedFramework> frameworks = new List <EmbeddedFramework>(); Console.WriteLine("Merging library build settings..."); foreach (var agg in libraryAndFeatureConfigs.Values) { EmbeddedFramework framework = new EmbeddedFramework { ID = agg.ID, UserFriendlyName = agg.Name, AdditionalSourceFiles = generator.ConvertPaths(Union(agg.AddedSettingsPerTargets.Values.Select(t => t.SourceFiles))), AdditionalHeaderFiles = generator.ConvertPaths(Union(agg.AddedSettingsPerTargets.Values.Select(t => t.HeaderFiles))), AdditionalIncludeDirs = generator.ConvertPaths(Intersect(agg.AddedSettingsPerTargets.Values.Select(t => t.IncludeDirectories))), AdditionalPreprocessorMacros = Intersect(agg.AddedSettingsPerTargets.Values.Select(t => t.EffectivePreprocessorMacros)), }; var properties = Union(agg.AddedSettingsPerTargets.Values.Select(t => t.EffectiveConfigurableProperties), new PropertyComparerByID()).ToList(); if (properties.Count > 0) { framework.ConfigurableProperties = new PropertyList { PropertyGroups = new List <PropertyGroup> { new PropertyGroup { UniqueID = "com.sysprogs.mbed.", Properties = properties } } } } ; foreach (var file in framework.AdditionalSourceFiles.Concat(framework.AdditionalHeaderFiles)) { var targetsWhereIncluded = agg.AddedSettingsPerTargets .Where(v => generator.ConvertPaths(v.Value.SourceFiles.Concat(v.Value.HeaderFiles)).Contains(file)) .Select(kv => kv.Key) .ToArray(); if (targetsWhereIncluded.Length == agg.AddedSettingsPerTargets.Count) { continue; //The file is included on all targets } fileConditions.Add(new FileCondition { FilePath = file, ConditionToInclude = new Condition.MatchesRegex { Expression = "$$SYS:MCU_ID$$", Regex = "^(" + string.Join("|", targetsWhereIncluded) + ")$" } }); } foreach (var kv in agg.AddedSettingsPerTargets) { var extraIncludeDirs = generator.ConvertPaths(kv.Value.IncludeDirectories).Except(framework.AdditionalIncludeDirs).ToArray(); var extraPreprocessorMacros = kv.Value.EffectivePreprocessorMacros.Except(framework.AdditionalPreprocessorMacros).ToArray(); if (extraIncludeDirs.Length == 0 && extraPreprocessorMacros.Length == 0) { continue; } ToolFlags flags = new ToolFlags(); if (extraIncludeDirs.Length > 0) { flags.IncludeDirectories = extraIncludeDirs; } if (extraPreprocessorMacros.Length > 0) { flags.PreprocessorMacros = extraPreprocessorMacros; } conditionalFlags.Add(new ConditionalToolFlags { Flags = flags, FlagCondition = new Condition.And { Arguments = new Condition[] { new Condition.ReferencesFramework { FrameworkID = framework.ID }, new Condition.Equals { Expression = "$$SYS:MCU_ID$$", ExpectedValue = kv.Key } } } }); } frameworks.Add(framework); } bsp.FileConditions = fileConditions.ToArray(); bsp.ConditionalFlags = conditionalFlags.ToArray(); bsp.Frameworks = frameworks.ToArray(); bsp.Examples = generator.DetectSampleDirs(); generator.ProduceBSPArchive(bsp); bool performTests = true; if (performTests) { RunTests(generator); } }
public void ConvertSoftdevicesAndPatchTarget(MCU mcu, string[] hexFiles) { string baseDir = Path.Combine(mbedRoot, "SysprogsGenerated"); Directory.CreateDirectory(baseDir); File.WriteAllText(Path.Combine(baseDir, ".mbedignore"), "*"); foreach (var hexFile in hexFiles) { if (_ConvertedHexFiles.ContainsKey(hexFile)) { continue; } var parsedFile = IntelHexParser.Parse(hexFile); string sectionName = Path.GetFileNameWithoutExtension(hexFile).Replace('.', '_').Replace('-', '_'); string generatedCFile = $@"{baseDir}\{Path.GetFileNameWithoutExtension(hexFile)}.c"; using (var fs = File.CreateText(generatedCFile)) { fs.WriteLine($"//Converted from " + Path.GetFileName(hexFile)); fs.WriteLine($"//Must be loaded at 0x{parsedFile.LoadAddress:x8}"); fs.WriteLine($"const char __attribute__((used, section(\".{sectionName}\"))) {sectionName}[] = " + "{"); fs.Write("\t"); int cnt = 0; foreach (var b in parsedFile.Data) { if (cnt != 0 && (cnt % 16) == 0) { fs.WriteLine(); fs.Write("\t"); } cnt++; fs.Write($"0x{b:x2}, "); } fs.WriteLine(); fs.WriteLine("};"); fs.WriteLine(); } if (!generatedCFile.StartsWith(mbedRoot, StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("HEX file outside mbed root"); } _ConvertedHexFiles[hexFile] = new ConvertedHexFile { LoadAddress = parsedFile.LoadAddress, RelativePath = generatedCFile.Substring(mbedRoot.Length + 1), SectionName = sectionName, Size = parsedFile.Data.Length }; } var hexFileList = hexFiles.Select(hf => _ConvertedHexFiles[hf]).ToList(); if (hexFiles.Length == 0) { return; } hexFileList.Sort((a, b) => a.LoadAddress.CompareTo(b.LoadAddress)); var linkerScript = mcu.CompilationFlags.LinkerScript; string patchedLinkerScript; if (!_PatchedLinkerScripts.TryGetValue(linkerScript, out patchedLinkerScript)) { patchedLinkerScript = Path.Combine(baseDir, Path.GetFileName(mcu.CompilationFlags.LinkerScript)); if (_PatchedLinkerScriptsReverse.TryGetValue(patchedLinkerScript, out string tmp) && tmp != linkerScript) { for (int i = 2; ; i++) { patchedLinkerScript = Path.Combine(baseDir, Path.GetFileNameWithoutExtension(mcu.CompilationFlags.LinkerScript) + "_x" + i + Path.GetExtension(mcu.CompilationFlags.LinkerScript)); if (!_PatchedLinkerScriptsReverse.ContainsKey(patchedLinkerScript)) { break; } } } _PatchedLinkerScripts[linkerScript] = patchedLinkerScript; _PatchedLinkerScriptsReverse[patchedLinkerScript] = linkerScript; List <string> linkerScriptLines = File.ReadAllLines(linkerScript.Replace("$$SYS:BSP_ROOT$$", mbedRoot)).ToList(); int firstMemorySectionLine = Enumerable.Range(0, linkerScript.Length) .SkipWhile(i => linkerScriptLines[i].Trim() != "MEMORY") .SkipWhile(i => !linkerScriptLines[i].Contains("{")) .First(); int offset = 1; foreach (var hex in hexFileList) { linkerScriptLines.Insert(firstMemorySectionLine + offset++, $" {hex.SectionName} (rx) : ORIGIN = 0x{hex.LoadAddress:x8}, LENGTH = 0x{hex.Size:x}"); } int sectionsLine = Enumerable.Range(0, linkerScript.Length) .SkipWhile(i => linkerScriptLines[i].Trim() != "SECTIONS") .SkipWhile(i => !linkerScriptLines[i].Contains("{")) .First(); offset = 1; foreach (var hex in hexFileList) { char br1 = '{', br2 = '}'; string contents = $".{hex.SectionName} :\n{br1}\n\tKEEP(*(.{hex.SectionName}))\n{br2} > {hex.SectionName}\n"; foreach (var line in contents.Split('\n')) { linkerScriptLines.Insert(sectionsLine + offset++, "\t" + line); } } File.WriteAllLines(patchedLinkerScript.Replace("$$SYS:BSP_ROOT$$", mbedRoot), linkerScriptLines); } mcu.CompilationFlags.LinkerScript = ConvertPaths(new[] { patchedLinkerScript })[0]; mcu.AdditionalSourceFiles = mcu.AdditionalSourceFiles.Concat(hexFileList.Select(h => "$$SYS:BSP_ROOT$$/" + h.RelativePath.Replace('\\', '/'))).ToArray(); }
public MCU GenerateDefinition(MCUFamilyBuilder fam, BSPBuilder bspBuilder, bool requirePeripheralRegisters) { if (string.IsNullOrEmpty(LinkerScriptPath)) { throw new Exception("Linker script not defined for " + Name); } if (string.IsNullOrEmpty(StartupFile)) { throw new Exception("Startup file not defined for " + Name); } if (string.IsNullOrEmpty(MCUDefinitionFile) && requirePeripheralRegisters) { throw new Exception("Peripheral register definition not found for " + Name); } var mcu = new MCU { ID = Name, FamilyID = fam.Definition.Name, FLASHSize = FlashSize, RAMSize = RAMSize, HierarchicalPath = string.Format(@"{0}\{1}", bspBuilder.ShortName, fam.Definition.Name), CompilationFlags = new ToolFlags { PreprocessorMacros = new string[] { bspBuilder.GetMCUTypeMacro(this) }, LinkerScript = LinkerScriptPath, }, AdditionalSourceFiles = new string[] { StartupFile }, MCUDefinitionFile = MCUDefinitionFile }; if (fam.Definition.HasMixedCores) { MCUFamilyBuilder.AddCoreSpecificFlags(true, mcu, Core); } List <SysVarEntry> sysVars = new List <SysVarEntry>(); foreach (var classifier in fam.Definition.Subfamilies) { string category = classifier.TryMatchMCUName(Name); if (category == null) { if (classifier.Required) { throw new Exception("Cannot detect subfamily for " + Name); } } sysVars.Add(new SysVarEntry { Key = classifier.VariableName, Value = category }); } if (sysVars.Count > 0) { mcu.AdditionalSystemVars = sysVars.ToArray(); } bspBuilder.GetMemoryBases(out mcu.FLASHBase, out mcu.RAMBase); return(mcu); }
public static MCU GenerateMCUDefinition(string bspDir, string linkerScript, string generatorResourceDir, string target, string debugComponentDir) { string mcuName = Path.GetFileNameWithoutExtension(linkerScript).TrimStart('D'); string copiedFilesDir = Path.Combine(bspDir, "DeviceFiles", mcuName); Directory.CreateDirectory(copiedFilesDir); File.Copy(linkerScript, Path.Combine(bspDir, "LinkerScripts", Path.GetFileName(linkerScript)), true); Dictionary <string, int> memorySizes = new Dictionary <string, int>(); Regex rgMemory = new Regex("^[ \t]+([^ ]+)[ \t]+:[ \t]+ORIGIN[ \t]*=[ \t]*0x([0-9a-fA-F]+),[ \t]*LENGTH[ \t]*=[ \t]*([0-9]+)"); foreach (var line in File.ReadAllLines(linkerScript)) { var m = rgMemory.Match(line); if (m.Success) { memorySizes[m.Groups[1].Value] = int.Parse(m.Groups[3].Value); } } List <string> headers = new List <string>(); foreach (var rf in RenamedFiles) { string file = Path.Combine(generatorResourceDir, string.Format(rf.SourceFileFormat, mcuName)); if (!File.Exists(file)) { Directory.Delete(copiedFilesDir, true); return(null); } var lines = File.ReadAllLines(file); if (rf.MakeWeakFunctions) { Regex rgFunc = new Regex("void[ \t]+(INT_[a-zA-Z0-9_]+)[ \t]*\\(void\\)"); for (int i = 0; i < lines.Length; i++) { var m = rgFunc.Match(lines[i]); if (m.Success) { lines[i] = lines[i].Substring(0, m.Groups[1].Index) + "__attribute__((weak)) " + lines[i].Substring(m.Groups[1].Index); } } } File.WriteAllLines(Path.Combine(copiedFilesDir, rf.TargetFileName), lines); if (rf.TargetFileName.EndsWith(".h")) { headers.Add($"$$SYS:BSP_ROOT$$/DeviceFiles/{mcuName}/rf.TargetFileName"); } } var mcu = new MCU { ID = mcuName, FamilyID = target, CompilationFlags = new ToolFlags { IncludeDirectories = new[] { $"$$SYS:BSP_ROOT$$/DeviceFiles/{mcuName}" }, LinkerScript = "$$SYS:BSP_ROOT$$/LinkerScripts/" + Path.GetFileName(linkerScript), LDFLAGS = "-nostartfiles -Wl,-e_PowerON_Reset", COMMONFLAGS = "$$com.sysprogs.renesas.doubles$$ $$com.sysprogs.renesas.core$$", }, AdditionalSourcesRequiredForTesting = true, AdditionalHeaderFiles = headers.ToArray() }; string peripheralFile = Path.Combine(debugComponentDir, "IoFiles", mcuName + ".sfrx"); if (File.Exists(peripheralFile)) { var doc = new XmlDocument(); doc.Load(peripheralFile); MCUDefinition definition = new MCUDefinition { MCUName = mcuName, RegisterSets = doc.DocumentElement.SelectNodes("moduletable/module").OfType <XmlElement>().Select(TransformRegisterSet).Where(s => s != null).ToArray() }; using (var fs = new FileStream(Path.Combine(bspDir, "DeviceDefinitions", mcuName + ".xml.gz"), FileMode.Create, FileAccess.Write)) using (var gs = new GZipStream(fs, CompressionMode.Compress)) XmlTools.SaveObjectToStream(definition, gs); mcu.MCUDefinitionFile = $"DeviceDefinitions/{mcuName}.xml"; } memorySizes.TryGetValue("ROM", out mcu.FLASHSize); memorySizes.TryGetValue("RAM", out mcu.RAMSize); return(mcu); }
static void GenerateBSP(string toolchainDir, string ccsDir) { string[] keys = null; string bspDir = toolchainDir + @"\msp430-bsp"; Dictionary <string, Dictionary <string, string> > tiMCUs = new Dictionary <string, Dictionary <string, string> >(StringComparer.CurrentCultureIgnoreCase); foreach (var line in File.ReadAllLines(@"..\..\msp430.csv")) { string[] cells = line.Split(';'); if (keys == null) { keys = cells; continue; } Dictionary <string, string> entry = new Dictionary <string, string>(); for (int i = 0; i < cells.Length; i++) { entry[keys[i]] = cells[i]; } tiMCUs[cells[0]] = entry; int idx = cells[0].IndexOf('-'); if (idx != -1) { tiMCUs[cells[0].Substring(0, idx)] = entry; } } Regex rgLen = new Regex(".*LENGTH = 0x([0-9a-fA-F]{4}).*"); Regex rgOrigin = new Regex(".*ORIGIN = 0x([0-9a-fA-F]{4}).*"); Regex rgPeriph = new Regex("__([^ ]+) = (0x[a-fA-F0-9]+);"); List <string> families = new List <string>(); List <MCU> MCUs = new List <MCU>(); List <MCUFamily> famList = new List <MCUFamily>(); Directory.CreateDirectory(bspDir); Directory.CreateDirectory(bspDir + "\\devices"); XmlSerializer regSer = new XmlSerializer(typeof(MCUDefinition)); string[] files = Directory.GetFiles(Path.Combine(toolchainDir, "include"), "*.h"); for (int i = 0; i < files.Length; i++) { string file = files[i]; var proc = new Process(); string mcuName = Path.GetFileNameWithoutExtension(file).ToLower(); proc.StartInfo.FileName = toolchainDir + @"\bin\msp430-elf-gcc.exe"; proc.StartInfo.Arguments = $"-I. -E {mcuName}.h -o - -mmcu={mcuName}"; proc.StartInfo.WorkingDirectory = Path.Combine(toolchainDir, "include"); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); List <string> lines = new List <string>(); for (; ;) { var line = proc.StandardOutput.ReadLine(); if (line == null) { break; } lines.Add(line); } proc.WaitForExit(); if (proc.ExitCode != 0) { continue; } List <HardwareRegister> regs = new List <HardwareRegister>(); MCU mcu = new MCU(); mcu.ID = mcuName; mcu.CompilationFlags.COMMONFLAGS = "-mmcu=" + mcuName; string ld = Path.ChangeExtension(file, ".ld"); if (!File.Exists(ld)) { continue; } foreach (var line in File.ReadAllLines(ld)) { if (line.StartsWith(" RAM")) { var m = rgLen.Match(line); mcu.RAMSize = int.Parse(m.Groups[1].ToString(), System.Globalization.NumberStyles.HexNumber); m = rgOrigin.Match(line); mcu.RAMBase = uint.Parse(m.Groups[1].ToString(), System.Globalization.NumberStyles.HexNumber); } if (line.StartsWith(" ROM")) { var m = rgLen.Match(line); mcu.FLASHSize = int.Parse(m.Groups[1].ToString(), System.Globalization.NumberStyles.HexNumber); m = rgOrigin.Match(line); mcu.FLASHBase = uint.Parse(m.Groups[1].ToString(), System.Globalization.NumberStyles.HexNumber); } } if (mcu.RAMSize == 0) { throw new Exception("RAM size cannot be 0"); } foreach (var line in lines) { Regex rgRegister = new Regex("extern volatile (.*) ([^ ]+) __asm__\\(\"([^\"]+)\"\\)"); var m = rgRegister.Match(line); if (!m.Success) { if (line.Contains("extern") && line.Contains("__asm__")) { throw new Exception("Suspicious line"); } continue; } string type = m.Groups[1].Value; string name = m.Groups[2].Value; if (name.EndsWith("_H") || name.EndsWith("_L")) { continue; } if (!m.Groups[3].Value.StartsWith("0x")) { throw new Exception("Invalid addr for " + name); } ulong addr = ulong.Parse(m.Groups[3].Value.Substring(2), System.Globalization.NumberStyles.HexNumber); HardwareRegister reg = new HardwareRegister(); // TODO: the registers are not all 8 bits // According to some datasheets (not all were checked): // 01FFh to 0100h -> 16 bits // 0FFh to 010h -> 8bits // 0Fh to 00h -> 8-bit SFR (special function register) if (type == "unsigned char") { reg.SizeInBits = 8; } else if (type == "unsigned int") { reg.SizeInBits = 16; } else if (type == "unsigned long int") { reg.SizeInBits = 32; } else { throw new Exception("Unknown type"); } reg.Name = name; reg.Address = m.Groups[3].Value; regs.Add(reg); } string family = "Other"; Dictionary <string, string> info; if (tiMCUs.TryGetValue(mcu.ID, out info)) { family = info["Description"]; } int idx = families.IndexOf(family); if (idx == -1) { idx = families.Count; families.Add(family); famList.Add(new MCUFamily { ID = "fam_" + idx, UserFriendlyName = family, CompilationFlags = null }); } mcu.FamilyID = "fam_" + idx.ToString(); mcu.MCUDefinitionFile = "devices\\" + mcu.ID + ".xml"; mcu.HierarchicalPath = family; MCUs.Add(mcu); MCUDefinition desc = new MCUDefinition { MCUName = mcu.ID, RegisterSets = new HardwareRegisterSet[] { new HardwareRegisterSet { Registers = regs.ToArray() } } }; //, Specs = specs }; AdjustHardwareRegisters(ccsDir, mcu.ID, ref desc.RegisterSets); using (var fs = File.Create(bspDir + "\\" + mcu.MCUDefinitionFile + ".gz")) using (var gs = new GZipStream(fs, CompressionMode.Compress)) regSer.Serialize(gs, desc); Console.WriteLine($"Processed {mcuName} ({i}/{files.Length}) [{i * 100 / files.Length}%]"); } //Build the XML file BoardSupportPackage bsp = new BoardSupportPackage { GNUTargetID = "msp430", PackageID = "com.sysprogs.msp430.core", PackageDescription = "MSP430 MCUs" }; bsp.SupportedMCUs = MCUs.ToArray(); bsp.MCUFamilies = famList.ToArray(); bsp.DebugMethodPackages = new string[] { "debuggers\\core", "debuggers\\mspdebug" }; bsp.Examples = new string[] { "Samples\\LEDBlink" }; #if BSP_ADDITIONAL_GCC_FLAGS bsp.AdditionalGCCFlags = new PropertyList { PropertyGroups = new PropertyGroup[] { new PropertyGroup { Name = "MSP430 Options", Properties = new PropertyEntry[] { new PropertyEntry.Boolean { Name = "Disable watchdog on startup", Description = "Link the crt0 modules that disable the watchdog on startup", UniqueID = "com.sysprogs.msp430.mdisable-watchdog", ValueForTrue = "-mdisable-watchdog", ValueForFalse = "", }, new PropertyEntry.Boolean { Name = "Enable libcalls for shifts", Description = "Use library routines for non-constant shifts", UniqueID = "com.sysprogs.msp430.menable-libcall-shift", ValueForTrue = "-menable-libcall-shift", ValueForFalse = "", }, new PropertyEntry.Boolean { Name = "Inline hardware multiplication", Description = "Issue inline multiplication code for 32-bit integers", UniqueID = "com.sysprogs.msp430.minline-hwmul", ValueForTrue = "-minline-hwmul", ValueForFalse = "", }, new PropertyEntry.Enumerated { Name = "Interrupt vector count", Description = "Specify number of interrupt vectors on chip:", UniqueID = "com.sysprogs.msp430.mivcnt", GNUPrefix = "-mivcnt=", SuggestionList = new PropertyEntry.Enumerated.Suggestion[] { new PropertyEntry.Enumerated.Suggestion { InternalValue = "", UserFriendlyName = "(default)" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "16" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "32" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "64" }, }, AllowFreeEntry = true, }, new PropertyEntry.Enumerated { Name = "Hardware multiplier", Description = "Define available hardware multiplier", UniqueID = "com.sysprogs.msp430.mmpy", GNUPrefix = "-mmpy=", SuggestionList = new PropertyEntry.Enumerated.Suggestion[] { new PropertyEntry.Enumerated.Suggestion { InternalValue = "", UserFriendlyName = "(default)" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "16" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "16se" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "32" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "32dw" }, } }, new PropertyEntry.Boolean { Name = "No hardware multiplication in ISRs", Description = "Assume interrupt routine does not do hardware multiplication", UniqueID = "com.sysprogs.msp430.noint-hwmul", ValueForTrue = "-noint-hwmul", ValueForFalse = "", }, new PropertyEntry.Boolean { Name = "Prologue space optimization", Description = "Use subroutine call for function prologue/epilogue when possible", UniqueID = "com.sysprogs.msp430.msave-prologue", ValueForTrue = "-msave-prologue", ValueForFalse = "", }, } } } }; #endif XmlSerializer ser = new XmlSerializer(typeof(BoardSupportPackage), PropertyEntry.EntryTypes); using (var fs = File.Create(bspDir + "\\BSP.xml")) ser.Serialize(fs, bsp); //mcuSelector1.Reset(); var lBsp = LoadedBSP.Load(new BSPSummary(bspDir), null); //mcuSelector1.AddBSP(lBsp); //embeddedDebugSettingsControl1.Reset(); //embeddedDebugSettingsControl1.AddDebugMethods(lBsp.KnownDebugMethods); }
/// <summary> /// Sets MCU family. Default is MSP430_F5xx. /// Please see TI BSL doc (slau319t.pdf) for supported MCUs and their modes. /// </summary> public Status SetMCU(MCU Mcu) { return(dev.SetMCU(Mcu) ?? Utils.StatusCreateEx(466)); }
/// <summary> /// /// </summary> /// <param name="extractedProjectDirectory"></param> /// <param name="sink"></param> /// <returns></returns> public static BoardSupportPackage GenerateBSPForSTARTProject(string extractedProjectDirectory, IWarningSink sink) { var gpdscFile = Path.Combine(extractedProjectDirectory, "AtmelStart.gpdsc"); if (!File.Exists(gpdscFile)) { throw new Exception($"{gpdscFile} does not exist!"); } var gccMakefile = Path.Combine(extractedProjectDirectory, "gcc\\Makefile"); if (!File.Exists(gccMakefile)) { throw new Exception($"{gccMakefile} does not exist. {GCCExportHint}"); } var xml = new XmlDocument(); xml.Load(gpdscFile); string device = null; foreach (var node in xml.SelectNodes("package/generators/generator/select").OfType <XmlElement>()) { var name = node.GetAttribute("Dname"); var vendor = node.GetAttribute("Dvendor"); if (!string.IsNullOrEmpty(vendor) && !string.IsNullOrEmpty(name)) { device = name; } } if (device == null) { throw new Exception($"Could not find the device ID in {gpdscFile}"); } var flagsFromMakefile = ScanMakefileForCommonFlags(gccMakefile); var bsp = new BoardSupportPackage { PackageID = "com.sysprogs.arm.samd21", GNUTargetID = "arm-eabi", PackageDescription = $"ATSAMD21 Support", BSPImporterID = ID, MCUFamilies = new[] { new MCUFamily { ID = "ATSAMD21" } }, Frameworks = xml.SelectNodes("package/components/component").OfType <XmlElement>().Select(GenerateFrameworkForComponent).Where(f => f != null).ToArray(), EmbeddedSamples = new[] { new EmbeddedProjectSample { Name = "Default Project", Description = "A basic project generated by Atmel START", AdditionalSourcesToCopy = new[] { new AdditionalSourceFile { SourcePath = "$$SYS:BSP_ROOT$$/main.c", TargetFileName = "$$PROJECTNAME$$.c", } } } } }; List <MCU> mcus = new List <MCU>(); Dictionary <string, int> headers = new Dictionary <string, int>(); string[] strFileMCU = File.ReadAllLines("../../McuAtmel.csv"); bool header_row = true; var linkerScripts = DetectLinkerScripts(extractedProjectDirectory); for (int il = 0; il < strFileMCU.Length; il++) { string line = strFileMCU[il]; string[] items = line.Split(','); if (header_row) { for (int i = 0; i < items.Length; i++) { headers[items[i]] = i; } header_row = false; continue; } String size = items[headers["Device Name"]].Substring(9, 2); String LinkerScriptLocation = linkerScripts.RelativeFLASHScript.Substring(0, linkerScripts.RelativeFLASHScript.LastIndexOf("/")) + "/samd21g" + size + "_flash.ld"; var memories = ScanLinkerScriptForMemories(Path.Combine(extractedProjectDirectory, LinkerScriptLocation)); LinkerScriptLocation = LinkerScriptLocation.Replace("*", "$$com.sysprogs.bspoptions.primary_memory$$"); LinkerScriptLocation = "$$SYS:BSP_ROOT$$/" + LinkerScriptLocation; var newMcu = new MCU { ID = items[headers["Device Name"]], FamilyID = "ATSAMD21", FLASHBase = (uint)0, FLASHSize = Int32.Parse(items[headers["Flash (kBytes)"]]), RAMBase = (uint)536870912, RAMSize = Int32.Parse(items[headers["SRAM (kBytes)"]]), CompilationFlags = new ToolFlags { PreprocessorMacros = new[] { $"__{items[headers["Device Name"]]}__" }, COMMONFLAGS = string.Join(" ", flagsFromMakefile.CommonFlags), LinkerScript = linkerScripts.LinkerScriptFormat, IncludeDirectories = flagsFromMakefile.RelativeIncludeDirs?.Select(d => "$$SYS:BSP_ROOT$$/" + d).ToArray(), LDFLAGS = "-Wl,--entry=Reset_Handler", //Unless this is specified explicitly, the gdb's "load" command won't set $pc to the entry point, requiring an explicit device reset. }, ConfigurableProperties = new PropertyList { PropertyGroups = new[] { linkerScripts.ToPropertyGroup() }.Where(g => g != null).ToList() }, MemoryMap = new AdvancedMemoryMap { Memories = memories.ToArray() } }; FixGPDSCErrors(bsp, newMcu, extractedProjectDirectory, flagsFromMakefile, linkerScripts.RelativeFLASHScript); mcus.Add(newMcu); } bsp.SupportedMCUs = mcus.ToArray(); List <AdditionalSourceFile> sourceFilesList = bsp.EmbeddedSamples[0].AdditionalSourcesToCopy.ToList(); IEnumerable <String> files = Directory.EnumerateFiles(extractedProjectDirectory); foreach (String item in files) { String target = ""; if (item.EndsWith(".h")) { target = "inc/" + Path.GetFileName(item); } else if (item.EndsWith(".c")) { target = "src/" + Path.GetFileName(item); } else { continue; } AdditionalSourceFile a = new AdditionalSourceFile { SourcePath = "$$SYS:BSP_ROOT$$/" + Path.GetFileName(item), TargetFileName = target, }; sourceFilesList.Add(a); } files = Directory.EnumerateFiles(extractedProjectDirectory + "/config"); foreach (String item in files) { String target = ""; if (item.EndsWith(".h")) { target = "config/" + Path.GetFileName(item); } else { continue; } AdditionalSourceFile a = new AdditionalSourceFile { SourcePath = "$$SYS:BSP_ROOT$$/config/" + Path.GetFileName(item), TargetFileName = target, }; sourceFilesList.Add(a); } bsp.EmbeddedSamples[0].AdditionalSourcesToCopy = sourceFilesList.ToArray(); String path = Path.Combine(extractedProjectDirectory, LoadedBSP.PackageFileName); XmlTools.SaveObject(bsp, path); return(bsp); }
static void Main(string[] args) { if (args.Length < 1) { throw new Exception("Usage: risc-v.exe <freedom-e-sdk directory with build logs>"); } const string TargetVariable = "com.sysprogs.riscv.target"; const string LinkerScriptVariant = "com.sysprogs.riscv.linkerscript"; string linkerScriptTemplate = $"$$SYS:BSP_ROOT$$/bsp/$${TargetVariable}$$/metal.$${LinkerScriptVariant}$$.lds"; const string FamilyName = "SIFIVE"; using (var bspBuilder = new RISCVBSPBuilder(new BSPDirectories(args[0], @"..\..\Output", @"..\..\rules", @"..\..\logs"))) { BoardSupportPackage bsp = new BoardSupportPackage { PackageID = "com.sysprogs.arm.riscv.sifive", PackageDescription = "SiFive Freedom E Devices", GNUTargetID = "riscv64-unknown-elf", RequiredToolchainID = "com.visualgdb.risc-v", GeneratedMakFileName = "sifive.mak", PackageVersion = "1.0", MinimumEngineVersion = "5.4", MCUFamilies = new[] { new MCUFamily { ID = FamilyName, CompilationFlags = new ToolFlags { IncludeDirectories = new[] { $"$$SYS:BSP_ROOT$$/bsp/$${TargetVariable}$$/install/include" }, LinkerScript = linkerScriptTemplate, AdditionalLibraries = new[] { "c", "gcc", "m" }, }, ConfigurableProperties = new PropertyList { PropertyGroups = new List <PropertyGroup> { new PropertyGroup { Properties = new List <PropertyEntry> { new PropertyEntry.Enumerated { UniqueID = LinkerScriptVariant, Name = "Default Linker Script", SuggestionList = new [] { "default", "freertos", "ramrodata", "scratchpad" }.Select(s => new PropertyEntry.Enumerated.Suggestion { InternalValue = s }).ToArray(), } } } } } } } }; List <MCU> mcus = new List <MCU>(); var commonPseudofamily = new MCUFamilyBuilder(bspBuilder, XmlTools.LoadObject <FamilyDefinition>(bspBuilder.Directories.RulesDir + @"\CommonFiles.xml")); List <MCUDefinitionWithPredicate> registers = new List <MCUDefinitionWithPredicate>(); foreach (var bspDir in Directory.GetDirectories(Path.Combine(bspBuilder.Directories.InputDir, "bsp"))) { var target = Path.GetFileName(bspDir); var logFile = Path.Combine(bspBuilder.Directories.InputDir, target + ".log"); if (!File.Exists(logFile)) { throw new Exception($"Missing {logFile}. Please run _buildall.sh in the SDK directory using WSL."); } var parsedLog = BuildLogFileParser.ParseRISCVBuildLog(logFile); if (parsedLog.LinkerScript == null) { throw new Exception("Unknown linker script"); } var script = bspBuilder.WSLPathToBSPPath(parsedLog.LinkerScript).Replace('/', '\\'); if (StringComparer.InvariantCultureIgnoreCase.Compare(script, linkerScriptTemplate.Replace($"$${TargetVariable}$$", target).Replace($"$${LinkerScriptVariant}$$", "default").Replace('/', '\\')) != 0) { throw new Exception("Unexpected linker script: " + script); } var memories = LinkerScriptTools.ScanLinkerScriptForMemories(script.Replace("$$SYS:BSP_ROOT$$", bspBuilder.Directories.InputDir)); var mcu = new MCU { ID = target.ToUpper(), UserFriendlyName = target.ToUpper(), FamilyID = FamilyName, MemoryMap = new AdvancedMemoryMap { Memories = memories, }, CompilationFlags = new ToolFlags { IncludeDirectories = parsedLog.allIncludes.Where(inc => inc != ".").Select(bspBuilder.WSLPathToBSPPath).ToArray(), PreprocessorMacros = parsedLog.allDefines.Where(kv => !kv.Key.StartsWith("PACKAGE")).Select(kv => $"{kv.Key}={kv.Value}").ToArray(), COMMONFLAGS = string.Join(" ", parsedLog.allFlags), LDFLAGS = string.Join(" ", parsedLog.AllLDFlags), }, AdditionalSystemVars = new[] { new SysVarEntry { Key = TargetVariable, Value = target, } }, RAMSize = (int)(memories.FirstOrDefault(m => m.Name == "ram")?.Size ?? 0), FLASHSize = (int)(memories.FirstOrDefault(m => m.Name == "rom")?.Size ?? 0), MCUDefinitionFile = $"DeviceDefinitions/{target.ToUpper()}.xml", }; if (mcu.RAMSize < 0) { mcu.RAMSize = 0; } var parsedSVD = SVDParser.ParseSVDFile(Path.Combine(bspDir, "design.svd"), target.ToUpper()); parsedSVD.MatchPredicate = new MCUPredicateImpl(mcu).Match; registers.Add(parsedSVD); commonPseudofamily.MCUs.Add(new MCUBuilder { Name = mcu.ID }); mcus.Add(mcu); } commonPseudofamily.AttachPeripheralRegisters(registers); bsp.SupportedMCUs = mcus.ToArray(); List <string> projectFiles = new List <string>(); PropertyList unused = null; if (commonPseudofamily.Definition.CoreFramework != null) { foreach (var job in commonPseudofamily.Definition.CoreFramework.CopyJobs) { job.CopyAndBuildFlags(bspBuilder, projectFiles, null, ref unused, null); } } bsp.Frameworks = commonPseudofamily.GenerateFrameworkDefinitions().ToArray(); var samples = commonPseudofamily.CopySamples(bsp.Frameworks).ToArray(); bsp.Examples = samples.Select(s => s.RelativePath).ToArray(); var mainFamily = bsp.MCUFamilies.First(); if (mainFamily.AdditionalSourceFiles != null || mainFamily.AdditionalHeaderFiles != null || bsp.FileConditions != null) { throw new Exception("TODO: merge lists"); } mainFamily.AdditionalSourceFiles = projectFiles.Where(f => !MCUFamilyBuilder.IsHeaderFile(f)).ToArray(); mainFamily.AdditionalHeaderFiles = projectFiles.Where(f => MCUFamilyBuilder.IsHeaderFile(f)).ToArray(); bsp.FileConditions = bspBuilder.MatchedFileConditions.Values.ToArray(); XmlTools.SaveObject(bsp, Path.Combine(bspBuilder.BSPRoot, "BSP.XML")); } }
public MCUPredicateImpl(MCU mcu) { _Mcu = mcu; }
private void get_mcu_type() { string file_list; int i = 0; int xml_size = 0; XmlNode MCU; XmlNode next; i = Xml_File.Count; XmlDocument doc = new XmlDocument(); for (i = 0; i < Xml_File.Count; i++) { file_list = Xml_File[i] as string; XmlDocument xmlDoc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(file_list, settings); xmlDoc.Load(reader); reader.Close(); string temp; ArrayList Xml_OPTION_Name = new ArrayList(); ArrayList Xml_OPTION_Value = new ArrayList(); ArrayList xml_option = new ArrayList(); XmlNode next2; XmlNode next3; XmlNode next4; int j = 0; try { MCU = xmlDoc.SelectSingleNode("MCU"); //xml_size = MCU.NextSibling; //mcu_tyep.CHIP_TYPE = (MCU.SelectSingleNode("/CHIP_TYPE")).InnerText; next = MCU.SelectSingleNode("CHIP_TYPE"); // UInt16 as1=StrToHex("0x001"); mcu_tyep.CHIP_TYPE = next.InnerText; mcu_tyep.CHIP_NAME = MCU.SelectSingleNode("CHIP_NAME").InnerText; mcu_tyep.CHIP_ID = StrToHex(MCU.SelectSingleNode("CHIP_ID").InnerText); mcu_tyep.ID_ADDR = StrToHex(MCU.SelectSingleNode("ID_ADDR").InnerText); mcu_tyep.USER_ROM_START = StrToHex(MCU.SelectSingleNode("USER_ROM_START").InnerText); mcu_tyep.USER_ROM_SIZE = StrToHex(MCU.SelectSingleNode("USER_ROM_SIZE").InnerText); mcu_tyep.CS_ADDR = StrToHex(MCU.SelectSingleNode("CS_ADDR").InnerText); mcu_tyep.CHIP_BIT = StrToHex(MCU.SelectSingleNode("CHIP_BIT").InnerText); // UInt16.Parse mcu_tyep.VDD = StrToHex(MCU.SelectSingleNode("VDD").InnerText); mcu_tyep.VPP = StrToHex(MCU.SelectSingleNode("VPP").InnerText); mcu_tyep.opbit = StrToHex(MCU.SelectSingleNode("opbit").InnerText); next = MCU.SelectSingleNode("OPTION"); for (j = 0; j < next.ChildNodes.Count; j++) { Xml_OPTION_Name.Add(next.ChildNodes[j].Name); next2 = next.SelectSingleNode(next.ChildNodes[j].Name); writer_data mcu_writer_data = new writer_data(); //烧录配置 mcu_writer_data.name = next.ChildNodes[j].Name; mcu_writer_data.addr = StrToHex((next2.SelectSingleNode("address").InnerText)); mcu_writer_data.Annotation.Clear(); string config_name; int start_bit = 0; int end_bit = 0; int bit_size = 0; //获取配置信息 for (int k = 1; k < next2.ChildNodes.Count; k++) { string[] config_bit = new string[50]; string[] config_value = new string[50]; Xml_OPTION_Value.Clear(); Xml_OPTION_Value.Add(next2.ChildNodes[k].Name); config_name = next2.ChildNodes[k].Name; next3 = next2.SelectSingleNode(next2.ChildNodes[k].Name); for (int l = 2; l < next3.ChildNodes.Count; l++) { Xml_OPTION_Value.Add(next3.ChildNodes[l].Name); config_bit[l - 2] = next3.ChildNodes[l].Name.Remove(0, 1); config_value[l - 2] = next3.SelectSingleNode(next3.ChildNodes[l].Name).InnerText; } string bit = next3.SelectSingleNode(next3.ChildNodes[1].Name).InnerText; int str_1 = bit.IndexOf('['); int str_2 = bit.IndexOf(':'); int str_3 = bit.IndexOf(']'); if (str_2 < 0) { start_bit = int.Parse(bit.Substring(str_1 + 1, str_3 - str_1 - 1)); end_bit = 0; bit_size = 1; } else { start_bit = int.Parse(bit.Substring(str_2 + 1, str_3 - str_2 - 1)); end_bit = int.Parse(bit.Substring(str_1 + 1, str_2 - str_1 - 1)); bit_size = end_bit - start_bit + 1; } mcu_writer_data.Annotation.Add(config_name); mcu_writer_data.Annotation.Add(start_bit); mcu_writer_data.Annotation.Add(end_bit); mcu_writer_data.Annotation.Add(bit_size); mcu_writer_data.Annotation.Add(config_bit); mcu_writer_data.Annotation.Add(config_value); } mcu_tyep.OPTION.Add(mcu_writer_data); //xml_option.Add(mcu_writer_data); //xml_option.AddRange(); } /* */ } catch (Exception e) { MessageBox.Show(null, "程序文件出错请重新安装。\n\n这个程序即将退出。", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); //throw e; Application.Exit();//退出程序 } Xml_Mcu.Add(mcu_tyep); } }
public static BoardSupportPackage GenerateBSPForSTARTProject(string extractedProjectDirectory, IWarningSink sink) { var gpdscFile = Path.Combine(extractedProjectDirectory, "AtmelStart.gpdsc"); if (!File.Exists(gpdscFile)) { throw new Exception($"{gpdscFile} does not exist!"); } var gccMakefile = Path.Combine(extractedProjectDirectory, "gcc\\Makefile"); if (!File.Exists(gccMakefile)) { throw new Exception($"{gccMakefile} does not exist. {GCCExportHint}"); } var xml = new XmlDocument(); xml.Load(gpdscFile); string device = null; foreach (var node in xml.SelectNodes("package/generators/generator/select").OfType <XmlElement>()) { var name = node.GetAttribute("Dname"); var vendor = node.GetAttribute("Dvendor"); if (!string.IsNullOrEmpty(vendor) && !string.IsNullOrEmpty(name)) { device = name; } } if (device == null) { throw new Exception($"Could not find the device ID in {gpdscFile}"); } var linkerScripts = DetectLinkerScripts(extractedProjectDirectory); var memories = ScanLinkerScriptForMemories(Path.Combine(extractedProjectDirectory, linkerScripts.RelativeFLASHScript)); var flagsFromMakefile = ScanMakefileForCommonFlags(gccMakefile); var mcu = new MCU { ID = device, FamilyID = "ATSTART", FLASHBase = (uint)(memories.FirstOrDefault(m => m.Name == "rom")?.Address ?? uint.MaxValue), FLASHSize = (int)(memories.FirstOrDefault(m => m.Name == "rom")?.Size ?? uint.MaxValue), RAMBase = (uint)(memories.FirstOrDefault(m => m.Name == "ram")?.Address ?? uint.MaxValue), RAMSize = (int)(memories.FirstOrDefault(m => m.Name == "ram")?.Size ?? uint.MaxValue), CompilationFlags = new ToolFlags { PreprocessorMacros = new[] { $"__{device}__" }, COMMONFLAGS = string.Join(" ", flagsFromMakefile.CommonFlags), LinkerScript = linkerScripts.LinkerScriptFormat, IncludeDirectories = flagsFromMakefile.RelativeIncludeDirs?.Select(d => "$$SYS:BSP_ROOT$$/" + d).ToArray(), LDFLAGS = "-Wl,--entry=Reset_Handler", //Unless this is specified explicitly, the gdb's "load" command won't set $pc to the entry point, requiring an explicit device reset. }, ConfigurableProperties = new PropertyList { PropertyGroups = new[] { linkerScripts.ToPropertyGroup() }.Where(g => g != null).ToList() }, MemoryMap = new AdvancedMemoryMap { Memories = memories.ToArray() } }; var bsp = new BoardSupportPackage { PackageID = "com.sysprogs.atstart." + device, GNUTargetID = "arm-eabi", PackageDescription = $"{device} Support", MCUFamilies = new[] { new MCUFamily { ID = "ATSTART" } }, SupportedMCUs = new[] { mcu }, Frameworks = xml.SelectNodes("package/components/component").OfType <XmlElement>().Select(GenerateFrameworkForComponent).Where(f => f != null).ToArray(), EmbeddedSamples = new[] { new EmbeddedProjectSample { Name = "Default Project", Description = "A basic project generated by Atmel START", AdditionalSourcesToCopy = new[] { new AdditionalSourceFile { SourcePath = "$$SYS:BSP_ROOT$$/main.c", TargetFileName = "$$PROJECTNAME$$.c", } } } } }; FixGPDSCErrors(bsp, mcu, extractedProjectDirectory, flagsFromMakefile, linkerScripts.RelativeFLASHScript); XmlTools.SaveObject(bsp, Path.Combine(extractedProjectDirectory, LoadedBSP.PackageFileName)); return(bsp); }