Example #1
0
        static void InsertRegisterValidationCode(string sourceFile, MCUDefinition mcuDefinition, LoadedRenamingRule[] renameRules, string[] pNonValidatedRegisters)
        {
            if (!File.Exists(sourceFile))
                throw new Exception("File does not exist: " + sourceFile);

            if (mcuDefinition != null)
            {
                using (var sw = new StreamWriter(sourceFile, true))
                {
                    sw.WriteLine();
                    sw.WriteLine("#define STATIC_ASSERT(COND) typedef char static_assertion[(COND)?1:-1]");
                    sw.WriteLine("void ValidateOffsets()");
                    sw.WriteLine("{");
                    foreach (var regset in mcuDefinition.RegisterSets)
                        foreach (var reg in regset.Registers)
                        {
                            string regName = reg.Name;
                            if (IsNoValid(regset.UserFriendlyName, pNonValidatedRegisters))
                                continue;

                            if (renameRules != null)
                                foreach (var rule in renameRules)
                                {
                                    if (rule.RegisterSetRegex?.IsMatch(regset.UserFriendlyName) != false)
                                    {
                                        var match = rule.RegisterRegex.Match(regName);
                                        if (match.Success)
                                        {
                                            switch (rule.Mode)
                                            {
                                                case RegisterRenamingMode.Normal:
                                                    regName = string.Format("{0}[{1}]", match.Groups[1], int.Parse(match.Groups[2].ToString()) + rule.Offset);
                                                    break;
                                                case RegisterRenamingMode.HighLow:
                                                    regName = string.Format("{0}[{1}]", match.Groups[1], match.Groups[2].ToString() == "H" ? 1 : 0);
                                                    break;
                                                case RegisterRenamingMode.WithSuffix:
                                                    regName = string.Format("{0}[{1}].{2}", match.Groups[1], int.Parse(match.Groups[2].ToString()) + rule.Offset, match.Groups[3]);
                                                    break;
                                            }
                                            break;
                                        }
                                    }
                                }

                            if (mcuDefinition.MCUName.StartsWith("MSP432"))
                            {
                                if (regName.Contains("RESERVED"))
                                    continue;
                                sw.WriteLine("STATIC_ASSERT((unsigned)&({0}->r{1}) == {2});", regset.UserFriendlyName, regName, reg.Address);
                            }
                            else
                                sw.WriteLine("STATIC_ASSERT((unsigned)&({0}->{1}) == {2});", regset.UserFriendlyName, regName, reg.Address);
                        }
                    sw.WriteLine("}");
                }
            }
        }
Example #2
0
        private static TestResult TestMCU(LoadedBSP.LoadedMCU mcu, string mcuDir, TestedSample sample, DeviceParameterSet extraParameters, LoadedRenamingRule[] renameRules, string[] nonValidateReg)
        {
            const int RepeatCount = 20;
            for (var i = 0; i < RepeatCount; ++i)
            {
                if (!Directory.Exists(mcuDir))
                {
                    break;
                }
                Console.WriteLine("Deleting " + mcuDir + "...");
                Directory.Delete(mcuDir, true);
                if (i == RepeatCount - 1)
                {
                    throw new Exception("Cannot remove folder!");
                }
                Thread.Sleep(50);
            }
            for (var i = 0; i < RepeatCount; ++i)
            {
                if (Directory.Exists(mcuDir))
                {
                    break;
                }
                Directory.CreateDirectory(mcuDir);
                if (i == RepeatCount - 1)
                {
                    throw new Exception("Cannot create folder!");
                }
                Thread.Sleep(50);
            }

            var configuredMCU = new LoadedBSP.ConfiguredMCU(mcu, GetDefaultPropertyValues(mcu.ExpandedMCU.ConfigurableProperties));
            if (configuredMCU.ExpandedMCU.FLASHSize == 0)
            {
                configuredMCU.Configuration["com.sysprogs.bspoptions.primary_memory"] = "sram";
            }

            var samples = mcu.BSP.GetSamplesForMCU(mcu.ExpandedMCU.ID, false);
            LoadedBSP.LoadedSample sampleObj;
            if (string.IsNullOrEmpty(sample.Name))
                sampleObj = samples[0];
            else
                sampleObj = samples.FirstOrDefault(s => s.Sample.Name == sample.Name);

            if (sampleObj == null)
            {
                if (sample.SkipIfNotFound)
                {
                    Directory.Delete(mcuDir, true);
                    return TestResult.Skipped;
                }
                else
                    throw new Exception("Cannot find sample: " + sample.Name);
            }

            string[] frameworks = sampleObj.Sample.RequiredFrameworks ?? new string[0];

            //frameworkCfg["com.sysprogs.bspoptions.stm32.freertos.heap"] = "heap_4";
            //frameworkCfg["com.sysprogs.bspoptions.stm32.freertos.portcore"] = "CM0";
            //frameworkCfg["com.sysprogs.bspoptions.stm32.usb.devclass"] = "CDC";
            //frameworkCfg["com.sysprogs.bspoptions.stm32.usb.speed"] = "FS";

            var configuredSample = new ConfiguredSample
            {
                Sample = sampleObj,
                Parameters = GetDefaultPropertyValues(sampleObj.Sample.ConfigurableProperties),
                Frameworks = (sampleObj.Sample.RequiredFrameworks == null) ? null :
                sampleObj.Sample.RequiredFrameworks.Select(fwId =>
                {
                    return configuredMCU.BSP.BSP.Frameworks.First(fwO => fwO.ID == fwId || fwO.ClassID == fwId && fwO.IsCompatibleWithMCU(configuredMCU.ExpandedMCU.ID));
                }).ToList(),
                FrameworkParameters = new Dictionary<string, string>(),
            };

            ApplyConfiguration(configuredMCU.Configuration, extraParameters?.MCUConfiguration, sample.MCUConfiguration);

            //configuredSample.Parameters["com.sysprogs.examples.ledblink.LEDPORT"] = "GPIOA";
            //configuredSample.Parameters["com.sysprogs.examples.stm32.LEDPORT"] = "GPIOA";
            //configuredSample.Parameters["com.sysprogs.examples.stm32.freertos.heap_size"] = "0";

            var bspDict = configuredMCU.BuildSystemDictionary(new BSPManager(), null);
            bspDict["PROJECTNAME"] = "test";

            if (configuredSample.Frameworks != null)
                foreach (var fw in configuredSample.Frameworks)
                {
                    if (fw.AdditionalSystemVars != null)
                        foreach (var kv in fw.AdditionalSystemVars)
                            bspDict[kv.Key] = kv.Value;
                    if (fw.ConfigurableProperties != null)
                    {
                        var defaultFwConfig = GetDefaultPropertyValues(fw.ConfigurableProperties);
                        if (defaultFwConfig != null)
                            foreach (var kv in defaultFwConfig)
                                configuredSample.FrameworkParameters[kv.Key] = kv.Value;
                    }
                }

            if (sampleObj.Sample?.DefaultConfiguration?.Entries != null)
                foreach (var kv in sampleObj.Sample.DefaultConfiguration.Entries)
                    configuredSample.FrameworkParameters[kv.Key] = kv.Value;

            ApplyConfiguration(configuredSample.FrameworkParameters, extraParameters?.FrameworkConfiguration, sample.FrameworkConfiguration);
            ApplyConfiguration(configuredSample.Parameters, extraParameters?.SampleConfiguration, sample.SampleConfiguration);

            var prj = new GeneratedProject(mcuDir, configuredMCU, frameworks);
            prj.DoGenerateProjectFromEmbeddedSample(configuredSample, false, bspDict);
            Dictionary<string, bool> frameworkIDs = new Dictionary<string, bool>();
            if (frameworks != null)
                foreach (var fw in frameworks)
                    frameworkIDs[fw] = true;
            if (sample.AdditionalFrameworks != null)
                foreach (var fw in sample.AdditionalFrameworks)
                    frameworkIDs[fw] = true;

            prj.AddBSPFilesToProject(bspDict, configuredSample.FrameworkParameters, frameworkIDs);
            var flags = prj.GetToolFlags(bspDict, configuredSample.FrameworkParameters, frameworkIDs);

            Dictionary<string, bool> sourceExtensions = new Dictionary<string, bool>(StringComparer.InvariantCultureIgnoreCase);
            foreach (var ext in sample.SourceFileExtensions.Split(';'))
                sourceExtensions[ext] = true;

            return BuildAndRunValidationJob(mcu, mcuDir, sample.ValidateRegisters, renameRules, prj, flags, sourceExtensions, nonValidateReg);
        }
Example #3
0
        private static TestResult BuildAndRunValidationJob(LoadedBSP.LoadedMCU mcu, string mcuDir, bool validateRegisters, LoadedRenamingRule[] renameRules, GeneratedProject prj, ToolFlags flags, Dictionary<string, bool> sourceExtensions, string[] nonValidateReg, BSPEngine.VendorSample vendorSample = null)
        {
            BuildJob job = new BuildJob();
            string prefix = string.Format("{0}\\{1}\\{2}-", mcu.BSP.Toolchain.Directory, mcu.BSP.Toolchain.Toolchain.BinaryDirectory, mcu.BSP.Toolchain.Toolchain.GNUTargetID);

            job.OtherTasks.Add(new BuildTask
            {
                Executable = prefix + "g++",
                Arguments = $"{flags.EffectiveLDFLAGS} $^ -o $@",
                AllInputs = prj.SourceFiles.Where(f => sourceExtensions.ContainsKey(Path.GetExtension(f).TrimStart('.')))
                .Select(f => Path.ChangeExtension(Path.GetFileName(f), ".o"))
                .Concat(prj.SourceFiles.Where(f => f.EndsWith(".a", StringComparison.InvariantCultureIgnoreCase)))
                .ToArray(),
                PrimaryOutput = "test.elf",
            });

            job.OtherTasks.Add(new BuildTask
            {
                Executable = prefix + "objcopy",
                Arguments = "-O binary $< $@",
                AllInputs = new[] { "test.elf" },
                PrimaryOutput = "test.bin",
            });

            foreach (var sf in prj.SourceFiles)
            {
                string ext = Path.GetExtension(sf);
                if (!sourceExtensions.ContainsKey(ext.TrimStart('.')))
                {
                    if (ext != ".txt")
                        Console.WriteLine($"#{sf} is not a recognized source file");
                }
                else
                {
                    bool isCpp = ext.ToLower() != ".c";
                    string obj = Path.ChangeExtension(Path.GetFileName(sf), ".o");
                    job.CompileTasks.Add(new BuildTask
                    {
                        PrimaryOutput = Path.ChangeExtension(Path.GetFileName(sf), ".o"),
                        AllInputs = new[] { sf },
                        Executable = prefix + (isCpp ? "g++" : "gcc"),
                        Arguments = $"-c $< {flags.GetEffectiveCFLAGS(isCpp)} -o {obj}",
                    });
                }
            }

            job.GenerateMakeFile(Path.Combine(mcuDir, "Makefile"), "test.bin");

            if (!string.IsNullOrEmpty(mcu.MCUDefinitionFile) && validateRegisters)
            {
                string firstSrcFileInPrjDir = prj.SourceFiles.First(fn => Path.GetDirectoryName(fn) == mcuDir);
                InsertRegisterValidationCode(firstSrcFileInPrjDir, XmlTools.LoadObject<MCUDefinition>(mcu.MCUDefinitionFile), renameRules, nonValidateReg);
            }

            Console.Write("Building {0}...", Path.GetFileName(mcuDir));
            bool buildSucceeded;
            if (false)
            {
                var proc = Process.Start(new ProcessStartInfo("cmd.exe", "/c " + Path.Combine(mcu.BSP.Toolchain.Directory, mcu.BSP.Toolchain.Toolchain.BinaryDirectory, "make.exe") + " -j" + Environment.ProcessorCount + " > build.log 2>&1") { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = mcuDir });
                proc.WaitForExit();
                buildSucceeded = proc.ExitCode == 0;
            }
            else
            {
                buildSucceeded = job.BuildFast(mcuDir, Environment.ProcessorCount);
            }

            bool success = false;
            string mapFile = Path.Combine(mcuDir, GeneratedProject.MapFileName);
            if (buildSucceeded && File.Exists(mapFile))
            {
                success = File.ReadAllLines(Path.Combine(mcuDir, mapFile)).Where(l => RgMainMap.IsMatch(l)).Count() > 0;

                if (success)
                {
                    string binFile = Path.Combine(mcuDir, "test.bin");
                    using (var fs = File.Open(binFile, FileMode.Open))
                        if (fs.Length < 512)
                            success = false;
                }
            }

            if (!success)
                return TestResult.Failed;

            if (vendorSample != null)
            {
                FillSampleDependenciesFromDepFiles(vendorSample, mcuDir);
            }

            Directory.Delete(mcuDir, true);
            return TestResult.Succeeded;
        }