IObjCopyToolPolicy.ObjCopy(
            ObjCopyModule sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString originalPath,
            Bam.Core.TokenizedString copiedPath)
        {
            var mode = (sender.Settings as IObjCopyToolSettings).Mode;

            // if linking debug data, add to the strip
            var meta = (EObjCopyToolMode.AddGNUDebugLink == mode) ? sender.SourceModule.MetaData as MakeFileBuilder.MakeFileMeta : new MakeFileBuilder.MakeFileMeta(sender);
            var rule = (EObjCopyToolMode.AddGNUDebugLink == mode) ? meta.Rules[0] :meta.AddRule();

            if (EObjCopyToolMode.AddGNUDebugLink == mode)
            {
                rule.AddOrderOnlyDependency(copiedPath.Parse());
            }
            else
            {
                meta.CommonMetaData.Directories.AddUnique(sender.CreateTokenizedString("@dir($(0))", copiedPath).Parse());

                var sourceFilename = System.IO.Path.GetFileName(originalPath.Parse());
                rule.AddTarget(copiedPath, variableName: "objcopy_" + sourceFilename);
                rule.AddPrerequisite(originalPath);
            }

            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            rule.AddShellCommand(System.String.Format("{0} {1} {2}",
                CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                commandLine.ToString(' '),
                CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
        }
Exemple #2
0
        ITarPolicy.CreateTarBall(
            TarBall sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool compiler,
            Bam.Core.TokenizedString scriptPath,
            Bam.Core.TokenizedString outputPath)
        {
            var tarPath = outputPath.ToString();
            var tarDir = System.IO.Path.GetDirectoryName(tarPath);
            if (!System.IO.Directory.Exists(tarDir))
            {
                System.IO.Directory.CreateDirectory(tarDir);
            }

            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            commandLine.Add("-c");
            commandLine.Add("-v");
            commandLine.Add("-T");
            commandLine.Add(scriptPath.Parse());
            commandLine.Add("-f");
            commandLine.Add(tarPath);
            CommandLineProcessor.Processor.Execute(context, compiler, commandLine);
        }
        ICompilationPolicy.Compile(
            ObjectFile sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString objectFilePath,
            Bam.Core.Module source)
        {
            var commandLineArgs = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLineArgs);

            var meta = new MakeFileBuilder.MakeFileMeta(sender);
            var rule = meta.AddRule();
            rule.AddTarget(objectFilePath);
            rule.AddPrerequisite(source, C.SourceFile.Key);

            var tool = sender.Tool as Bam.Core.ICommandLineTool;
            var command = new System.Text.StringBuilder();
            command.AppendFormat("{0} {1} $< {2}",
                CommandLineProcessor.Processor.StringifyTool(tool),
                commandLineArgs.ToString(' '),
                CommandLineProcessor.Processor.TerminatingArgs(tool));
            rule.AddShellCommand(command.ToString());

            var objectFileDir = System.IO.Path.GetDirectoryName(objectFilePath.ToString());
            meta.CommonMetaData.Directories.AddUnique(objectFileDir);
            meta.CommonMetaData.ExtendEnvironmentVariables(tool.EnvironmentVariables);
        }
Exemple #4
0
        void IRccGenerationPolicy.Rcc(
            RccGeneratedSource sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool rccCompiler,
            Bam.Core.TokenizedString generatedRccSource,
            QRCFile source)
        {
            var encapsulating = sender.GetEncapsulatingReferencedModule();

            var solution = Bam.Core.Graph.Instance.MetaData as VSSolutionBuilder.VSSolution;
            var project = solution.EnsureProjectExists(encapsulating);
            var config = project.GetConfiguration(encapsulating);

            var output = generatedRccSource.Parse();

            var args = new Bam.Core.StringArray();
            args.Add(CommandLineProcessor.Processor.StringifyTool(rccCompiler));
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(args);
            args.Add(System.String.Format("-o {0}", output));
            args.Add("%(FullPath)");

            config.AddOtherFile(source);

            var customBuild = config.GetSettingsGroup(VSSolutionBuilder.VSSettingsGroup.ESettingsGroup.CustomBuild, include: source.InputPath, uniqueToProject: true);
            customBuild.AddSetting("Command", args.ToString(' '), condition: config.ConditionText);
            customBuild.AddSetting("Message", System.String.Format("Rccing {0}", System.IO.Path.GetFileName(source.InputPath.Parse())), condition: config.ConditionText);
            customBuild.AddSetting("Outputs", output, condition: config.ConditionText);
        }
Exemple #5
0
        void IGeneratedSourcePolicy.GenerateSource(
            GeneratedSourceModule sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool compiler,
            Bam.Core.TokenizedString generatedFilePath)
        {
            var encapsulating = sender.GetEncapsulatingReferencedModule();

            var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta;
            var target = workspace.EnsureTargetExists(encapsulating);
            var configuration = target.GetConfiguration(encapsulating);

            var command = new System.Text.StringBuilder();
            // recode the executable path for Xcode
            var xcodePath = encapsulating.CreateTokenizedString("$(packagebuilddir)/$(config)").Parse();
            xcodePath += "/" + System.IO.Path.GetFileName(compiler.Executable.Parse());
            command.AppendFormat(xcodePath);
            // TODO: change this to a configuration directory really
            command.AppendFormat(" {0}", Bam.Core.TokenizedString.Create("$(buildroot)", null).Parse());
            command.AppendFormat(" {0}", "Generated");

            var commands = new Bam.Core.StringArray();
            commands.Add(command.ToString());
            target.AddPreBuildCommands(commands, configuration);

            var compilerTarget = workspace.EnsureTargetExists(compiler as Bam.Core.Module);
            target.Requires(compilerTarget);
        }
Exemple #6
0
        void IMocGenerationPolicy.Moc(
            MocGeneratedSource sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool mocCompiler,
            Bam.Core.TokenizedString generatedMocSource,
            C.HeaderFile source)
        {
            var encapsulating = sender.GetEncapsulatingReferencedModule();

            var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta;
            var target = workspace.EnsureTargetExists(encapsulating);
            var configuration = target.GetConfiguration(encapsulating);

            var output = generatedMocSource.Parse();
            var sourcePath = source.InputPath.Parse();

            var commands = new Bam.Core.StringArray();
            commands.Add(System.String.Format("[[ ! -d {0} ]] && mkdir -p {0}", System.IO.Path.GetDirectoryName(output)));

            var args = new Bam.Core.StringArray();
            args.Add(CommandLineProcessor.Processor.StringifyTool(mocCompiler));
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(args);
            args.Add(System.String.Format("-o {0}", output));
            args.Add(sourcePath);

            var moc_commandLine = args.ToString(' ');

            commands.Add(System.String.Format("if [[ ! -e {0} || {1} -nt {0} ]]", output, sourcePath));
            commands.Add("then");
            commands.Add(System.String.Format("\techo {0}", moc_commandLine));
            commands.Add(System.String.Format("\t{0}", moc_commandLine));
            commands.Add("fi");

            target.AddPreBuildCommands(commands, configuration);
        }
        ICollatedObjectPolicy.Collate(
            CollatedObject sender,
            Bam.Core.ExecutionContext context)
        {
            var sourcePath = sender.SourcePath;
            if (null == sender.Reference)
            {
                // the main file is not copied anywhere, as we copy required files around it where VS wrote the main file
                // this is managed by the Collation class, querying the build mode for where publishing is relative to
                // ignore any subdirectory on this module
                return;
            }

            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            if (sender.SourceModule != null && sender.SourceModule.MetaData != null)
            {
                var destinationPath = sender.Macros["CopyDir"].Parse();

                var commands = new Bam.Core.StringArray();
                commands.Add(System.String.Format("IF NOT EXIST {0} MKDIR {0}", destinationPath));
                commands.Add(System.String.Format(@"{0} {1} $(OutputPath)$(TargetFileName) {2} {3}",
                    CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                    commandLine.ToString(' '),
                    destinationPath,
                    CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));

                var project = sender.SourceModule.MetaData as VSSolutionBuilder.VSProject;
                var config = project.GetConfiguration(sender.SourceModule);
                config.AddPostBuildCommands(commands);
            }
            else
            {
                var commands = new Bam.Core.StringArray();
                if (sender is CollatedDirectory)
                {
                    // Windows XCOPY requires the directory name to be added to the destination, while Posix cp does not
                    commands.Add(System.String.Format(@"{0} {1} {2} $(OutDir){3}\ {4}",
                        CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                        commandLine.ToString(' '),
                        sourcePath.ParseAndQuoteIfNecessary(),
                        sender.CreateTokenizedString("$(0)/@ifnotempty($(CopiedFilename),$(CopiedFilename),@filename($(1)))", sender.SubDirectory, sourcePath).Parse(),
                        CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                }
                else
                {
                    commands.Add(System.String.Format(@"{0} {1} {2} $(OutDir){3}\ {4}",
                        CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                        commandLine.ToString(' '),
                        sourcePath.ParseAndQuoteIfNecessary(),
                        sender.SubDirectory,
                        CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                }

                var project = sender.Reference.SourceModule.MetaData as VSSolutionBuilder.VSProject;
                var config = project.GetConfiguration(sender.Reference.SourceModule);
                config.AddPostBuildCommands(commands);
            }
        }
Exemple #8
0
        static Configure()
        {
            var graph = Bam.Core.Graph.Instance;
            var qtPackage = graph.Packages.FirstOrDefault(item => item.Name == "Qt");
            if (null == qtPackage)
            {
                throw new Bam.Core.Exception("Unable to locate Qt package for this build");
            }
            var qtVersion = qtPackage.Version;
            Version = new Bam.Core.StringArray(qtVersion.Split(new [] {'.'}));

            var qtInstallDir = Bam.Core.CommandLineProcessor.Evaluate(new Options.QtInstallPath());
            if (!System.IO.Directory.Exists(qtInstallDir))
            {
                throw new Bam.Core.Exception("Qt install dir, {0}, does not exist", qtInstallDir);
            }
            InstallPath = Bam.Core.TokenizedString.CreateVerbatim(qtInstallDir);

            if (Bam.Core.OSUtilities.IsWindowsHosting)
            {
                ExecutableExtension = Bam.Core.TokenizedString.CreateVerbatim(".exe");
            }
            else
            {
                ExecutableExtension = Bam.Core.TokenizedString.CreateVerbatim(string.Empty);
            }
        }
        IArchivingPolicy.Archive(
            StaticLibrary sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString libraryPath,
            System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> objectFiles,
            System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> headers)
        {
            var commandLineArgs = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLineArgs);

            var meta = new MakeFileBuilder.MakeFileMeta(sender);
            var rule = meta.AddRule();
            rule.AddTarget(libraryPath);
            foreach (var input in objectFiles)
            {
                rule.AddPrerequisite(input, C.ObjectFile.Key);
            }

            var tool = sender.Tool as Bam.Core.ICommandLineTool;
            var command = new System.Text.StringBuilder();
            command.AppendFormat("{0} {1} $^ {2}",
                CommandLineProcessor.Processor.StringifyTool(tool),
                commandLineArgs.ToString(' '),
                CommandLineProcessor.Processor.TerminatingArgs(tool));
            rule.AddShellCommand(command.ToString());

            var libraryFileDir = System.IO.Path.GetDirectoryName(libraryPath.ToString());
            meta.CommonMetaData.Directories.AddUnique(libraryFileDir);
            meta.CommonMetaData.ExtendEnvironmentVariables(tool.EnvironmentVariables);
        }
Exemple #10
0
 Convert(
     System.Type conversionClass,
     Bam.Core.Settings toolSettings,
     Bam.Core.StringArray commandLine)
 {
     var stringArrayType = typeof(Bam.Core.StringArray);
     foreach (var i in toolSettings.Interfaces())
     {
         var method = conversionClass.GetMethod("Convert", new[] { i, stringArrayType });
         if (null == method)
         {
             throw new Bam.Core.Exception("Unable to locate method {0}.Convert({1}, {2})",
                 conversionClass.ToString(),
                 i.ToString(),
                 stringArrayType);
         }
         var commands = new Bam.Core.StringArray();
         try
         {
             method.Invoke(null, new object[] { toolSettings, commands });
         }
         catch (System.Reflection.TargetInvocationException exception)
         {
             throw new Bam.Core.Exception(exception.InnerException, "Command line conversion error:");
         }
         commandLine.AddRange(commands);
     }
 }
Exemple #11
0
        public object Build(
            XmlUtilities.XmlModule moduleToBuild,
            out bool success)
        {
            var node = moduleToBuild.OwningNode;

            var xmlLocation = moduleToBuild.Locations[XmlUtilities.XmlModule.OutputFile];
            var xmlPath = xmlLocation.GetSinglePath();
            if (null == xmlPath)
            {
                throw new Bam.Core.Exception("XML output path was not set");
            }

            // dependency checking
            {
                var outputFiles = new Bam.Core.StringArray();
                outputFiles.Add(xmlPath);
                if (!RequiresBuilding(outputFiles, new Bam.Core.StringArray()))
                {
                    Bam.Core.Log.DebugMessage("'{0}' is up-to-date", node.UniqueModuleName);
                    success = true;
                    return null;
                }
            }

            Bam.Core.Log.Info("Writing XML file '{0}'", xmlPath);

            // create all directories required
            var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist);
            foreach (var dir in dirsToCreate)
            {
                var dirPath = dir.GetSinglePath();
                NativeBuilder.MakeDirectory(dirPath);
            }

            // serialize the XML to disk
            var settings = new System.Xml.XmlWriterSettings();
            settings.CheckCharacters = true;
            settings.CloseOutput = true;
            settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto;
            settings.Indent = true;
            settings.IndentChars = new string(' ', 4);
            settings.NewLineChars = "\n";
            settings.NewLineHandling = System.Xml.NewLineHandling.None;
            settings.NewLineOnAttributes = false;
            settings.OmitXmlDeclaration = false;
            settings.Encoding = new System.Text.UTF8Encoding(false); // do not write BOM

            using (var xmlWriter = System.Xml.XmlWriter.Create(xmlPath, settings))
            {
                moduleToBuild.Document.WriteTo(xmlWriter);
                xmlWriter.WriteWhitespace(settings.NewLineChars);
            }

            success = true;
            return null;
        }
Exemple #12
0
        public object Build(
            XmlUtilities.XmlModule moduleToBuild,
            out bool success)
        {
            var isPlist = moduleToBuild is XmlUtilities.OSXPlistModule;
            var locationMap = moduleToBuild.Locations;
            var outputDir = locationMap[XmlUtilities.OSXPlistModule.OutputDir];
            var outputDirPath = outputDir.GetSingleRawPath();

            if (!System.IO.Directory.Exists(outputDirPath))
            {
                System.IO.Directory.CreateDirectory(outputDirPath);
            }

            var xmlFileLoc = locationMap[XmlUtilities.XmlModule.OutputFile];
            var xmlFilePath = xmlFileLoc.GetSingleRawPath();

            // write a script that can be invoked by the MakeFile to generate the XML file
            var shellScriptLeafName = isPlist ? "writePList.py" : "writeXMLFile.py";
            var shellScriptLoc = Bam.Core.FileLocation.Get(outputDir, shellScriptLeafName, Bam.Core.Location.EExists.WillExist);
            var shellScriptPath = shellScriptLoc.GetSingleRawPath();
            XmlUtilities.XmlDocumentToPythonScript.Write(moduleToBuild.Document, shellScriptPath, xmlFilePath);

            var node = moduleToBuild.OwningNode;
            var makeFile = new MakeFile(node, this.topLevelMakeFilePath);

            var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist);

            var recipe = new Bam.Core.StringArray();
            recipe.Add(System.String.Format("$(shell python {0})", shellScriptPath));

            var rule = new MakeFileRule(
                moduleToBuild,
                XmlUtilities.XmlModule.OutputFile,
                node.UniqueModuleName,
                dirsToCreate,
                null,
                null,
                recipe);
            rule.OutputLocationKeys = new Bam.Core.Array<Bam.Core.LocationKey>(XmlUtilities.XmlModule.OutputFile);
            makeFile.RuleArray.Add(rule);

            var makeFilePath = MakeFileBuilder.GetMakeFilePathName(node);
            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(makeFilePath));

            using (var makeFileWriter = new System.IO.StreamWriter(makeFilePath))
            {
                makeFile.Write(makeFileWriter);
            }

            var exportedTargets = makeFile.ExportedTargets;
            var exportedVariables = makeFile.ExportedVariables;
            var returnData = new MakeFileData(makeFilePath, exportedTargets, exportedVariables, null);
            success = true;
            return returnData;
        }
Exemple #13
0
        public object Build(
            CodeGenTest2.CodeGenModule moduleToBuild,
            out bool success)
        {
            var codeGenModuleModule = moduleToBuild as Bam.Core.BaseModule;
            var node = codeGenModuleModule.OwningNode;
            var target = node.Target;
            var codeGenModuleOptions = codeGenModuleModule.Options;
            var toolOptions = codeGenModuleOptions as CodeGenTest2.CodeGenOptionCollection;
            var tool = target.Toolset.Tool(typeof(CodeGenTest2.ICodeGenTool));

            // dependency checking
            {
                var inputLocations = new Bam.Core.LocationArray(
                    Bam.Core.FileLocation.Get(tool.Executable((Bam.Core.BaseTarget)target), Bam.Core.Location.EExists.WillExist)
                    );
                var outputLocations = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.File, Bam.Core.Location.EExists.WillExist);
                if (!RequiresBuilding(outputLocations, inputLocations))
                {
                    Bam.Core.Log.DebugMessage("'{0}' is up-to-date", node.UniqueModuleName);
                    success = true;
                    return null;
                }
            }

            // at this point, we know the node outputs need building

            // create all directories required
            var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist);
            foreach (var dir in dirsToCreate)
            {
                var dirPath = dir.GetSinglePath();
                NativeBuilder.MakeDirectory(dirPath);
            }

            var commandLineBuilder = new Bam.Core.StringArray();
            if (toolOptions is CommandLineProcessor.ICommandLineSupport)
            {
                var commandLineOption = toolOptions as CommandLineProcessor.ICommandLineSupport;
                commandLineOption.ToCommandLineArguments(commandLineBuilder, target, null);
            }
            else
            {
                throw new Bam.Core.Exception("CodeGen options does not support command line translation");
            }

            string hostApplication = null;
            if (target.HasPlatform(Bam.Core.EPlatform.OSX))
            {
                hostApplication = "mono";
            }
            var exitCode = CommandLineProcessor.Processor.Execute(node, tool, commandLineBuilder, hostApplication);
            success = (0 == exitCode);

            return null;
        }
Exemple #14
0
 INSISPolicy.CreateInstaller(
     NSISInstaller sender,
     Bam.Core.ExecutionContext context,
     Bam.Core.ICommandLineTool compiler,
     Bam.Core.TokenizedString scriptPath)
 {
     var args = new Bam.Core.StringArray();
     args.Add(scriptPath.Parse());
     CommandLineProcessor.Processor.Execute(context, compiler, args);
 }
        IInstallNameToolPolicy.InstallName(
            InstallNameModule sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString oldName,
            Bam.Core.TokenizedString newName)
        {
            var originalModule = sender.Source.SourceModule;
            if (originalModule == null)
            {
                return;
            }

            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            var commands = new Bam.Core.StringArray();

            if (sender.Source.SourceModule != null && sender.Source.SourceModule.MetaData != null)
            {
                commands.Add(System.String.Format("{0} {1} {2} {3} {4} {5}",
                    CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                    commandLine.ToString(' '),
                    oldName.Parse(),
                    newName.Parse(),
                    sender.Source.GeneratedPaths[CollatedObject.Key].Parse(),
                    CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));

                var target = sender.Source.SourceModule.MetaData as XcodeBuilder.Target;
                var configuration = target.GetConfiguration(sender.Source.SourceModule);
                target.AddPostBuildCommands(commands, configuration);
            }
            else
            {
                var destinationFolder = "$CONFIGURATION_BUILD_DIR";
                if (sender.Source.Reference != null)
                {
                    destinationFolder = "$CONFIGURATION_BUILD_DIR/$EXECUTABLE_FOLDER_PATH";
                }

                commands.Add(System.String.Format("{0} {1} {2} {3} {4}/{5} {6}",
                    CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                    commandLine.ToString(' '),
                    oldName.Parse(),
                    newName.Parse(),
                    destinationFolder,
                    sender.Source.CreateTokenizedString("$(0)/@filename($(1))", sender.Source.SubDirectory, sender.Source.SourcePath).Parse(),
                    CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));

                var target = sender.Source.Reference.SourceModule.MetaData as XcodeBuilder.Target;
                var configuration = target.GetConfiguration(sender.Source.Reference.SourceModule);
                target.AddPostBuildCommands(commands, configuration);
            }
        }
 IChangeRPathPolicy.Change(
     ChangeRPathModule sender,
     Bam.Core.ExecutionContext context,
     CollatedFile source,
     string newRPath)
 {
     var commandLine = new Bam.Core.StringArray();
     commandLine.Add("-r");
     commandLine.Add(newRPath);
     commandLine.Add(source.GeneratedPaths[CollatedObject.Key].Parse());
     CommandLineProcessor.Processor.Execute(context, sender.Tool as Bam.Core.ICommandLineTool, commandLine);
 }
Exemple #17
0
 void IGeneratedSourcePolicy.GenerateSource(
     GeneratedSourceModule sender,
     Bam.Core.ExecutionContext context,
     Bam.Core.ICommandLineTool compiler,
     Bam.Core.TokenizedString generatedFilePath)
 {
     var args = new Bam.Core.StringArray();
     // TODO: change this to a configuration directory really
     args.Add(Bam.Core.TokenizedString.Create("$(buildroot)", null).Parse());
     args.Add("Generated");
     CommandLineProcessor.Processor.Execute(context, compiler, args);
 }
        IInstallNameToolPolicy.InstallName(
            InstallNameModule sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString oldName,
            Bam.Core.TokenizedString newName)
        {
            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            commandLine.Add(newName.Parse());
            commandLine.Add(sender.Source.GeneratedPaths[CollatedObject.Key].Parse());
            CommandLineProcessor.Processor.Execute(context, sender.Tool as Bam.Core.ICommandLineTool, commandLine);
        }
Exemple #19
0
        public MetaData()
        {
            if (!Bam.Core.OSUtilities.IsOSXHosting)
            {
                return;
            }

            this.Meta.Add("LastUpgradeCheck", "0640");

            var expectedSDKs = new Bam.Core.StringArray("macosx10.9", "macosx10.10");
            this.SDK = ClangCommon.ConfigureUtilities.SetSDK(expectedSDKs, this.Contains("SDK") ? this.SDK : null);
            if (!this.Contains("MinVersion"))
            {
                this.MinimumVersionSupported = this.SDK;
            }
        }
Exemple #20
0
        IObjCopyToolPolicy.ObjCopy(
            ObjCopyModule sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString originalPath,
            Bam.Core.TokenizedString copiedPath)
        {
            var copiedDir = System.IO.Path.GetDirectoryName(copiedPath.Parse());
            if (!System.IO.Directory.Exists(copiedDir))
            {
                System.IO.Directory.CreateDirectory(copiedDir);
            }

            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);
            CommandLineProcessor.Processor.Execute(context, sender.Tool as Bam.Core.ICommandLineTool, commandLine);
        }
        ICollatedObjectPolicy.Collate(
            CollatedObject sender,
            Bam.Core.ExecutionContext context)
        {
            if (sender is CollatedFile)
            {
                if (!(sender as CollatedFile).FailWhenSourceDoesNotExist)
                {
                    var source = sender.SourcePath.Parse();
                    if (!System.IO.File.Exists(source))
                    {
                        Bam.Core.Log.Detail("File {0} cannot be copied as it does not exist. Ignoring.", source);
                        return;
                    }
                }
            }

            var isSymLink = (sender is CollatedSymbolicLink);
            var sourcePath = isSymLink ? sender.Macros["LinkTarget"] : sender.SourcePath;

            var destinationPath = isSymLink ? sender.GeneratedPaths[CollatedObject.Key].Parse() : sender.Macros["CopyDir"].Parse();

            if (!isSymLink)
            {
                // synchronize, so that multiple modules don't try to create the same directories simultaneously
                lock ((sender.Reference != null) ? sender.Reference : sender)
                {
                    if (!System.IO.Directory.Exists(destinationPath))
                    {
                        System.IO.Directory.CreateDirectory(destinationPath);
                    }
                }
            }

            var copySource = sourcePath.ParseAndQuoteIfNecessary();
            if (sender is CollatedDirectory && sender.Tool is CopyFilePosix & sender.Macros["CopiedFilename"].IsAliased)
            {
                copySource = System.String.Format("{0}/*", copySource);
            }

            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            commandLine.Add(copySource);
            commandLine.Add(destinationPath);
            CommandLineProcessor.Processor.Execute(context, sender.Tool as Bam.Core.ICommandLineTool, commandLine);
        }
Exemple #22
0
        IStripToolPolicy.Strip(
            StripModule sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString originalPath,
            Bam.Core.TokenizedString strippedPath)
        {
            var strippedDir = System.IO.Path.GetDirectoryName(strippedPath.Parse());
            if (!System.IO.Directory.Exists(strippedDir))
            {
                System.IO.Directory.CreateDirectory(strippedDir);
            }

            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);
            commandLine.Add(originalPath.Parse());
            commandLine.Add(System.String.Format("-o {0}", strippedPath.Parse()));
            CommandLineProcessor.Processor.Execute(context, sender.Tool as Bam.Core.ICommandLineTool, commandLine);
        }
Exemple #23
0
        public object Build(
            XmlUtilities.TextFileModule moduleToBuild,
            out bool success)
        {
            var node = moduleToBuild.OwningNode;

            var outputLoc = moduleToBuild.Locations[XmlUtilities.TextFileModule.OutputFile];
            var outputPath = outputLoc.GetSinglePath();
            if (null == outputPath)
            {
                throw new Bam.Core.Exception("Text output path was not set");
            }

            // dependency checking
            {
                var outputFiles = new Bam.Core.StringArray();
                outputFiles.Add(outputPath);
                if (!RequiresBuilding(outputFiles, new Bam.Core.StringArray()))
                {
                    Bam.Core.Log.DebugMessage("'{0}' is up-to-date", node.UniqueModuleName);
                    success = true;
                    return null;
                }
            }

            Bam.Core.Log.Info("Writing text file '{0}'", outputPath);

            // create all directories required
            var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist);
            foreach (var dir in dirsToCreate)
            {
                var dirPath = dir.GetSinglePath();
                NativeBuilder.MakeDirectory(dirPath);
            }

            using (var writer = new System.IO.StreamWriter(outputPath, false, System.Text.Encoding.ASCII))
            {
                var content = moduleToBuild.Content.ToString();
                writer.Write(content);
            }

            success = true;
            return null;
        }
        IInstallNameToolPolicy.InstallName(
            InstallNameModule sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString oldName,
            Bam.Core.TokenizedString newName)
        {
            // add another shell command to the rule for copying the file
            var meta = sender.Source.MetaData as MakeFileBuilder.MakeFileMeta;
            var rule = meta.Rules[0];

            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            rule.AddShellCommand(System.String.Format(@"{0} {1} {2} $@ {3}",
                CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                commandLine.ToString(' '),
                newName.Parse(),
                CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
        }
        IChangeRPathPolicy.Change(
            ChangeRPathModule sender,
            Bam.Core.ExecutionContext context,
            CollatedFile source,
            string newRPath)
        {
            // add another shell command to the rule for copying the file
            var meta = source.MetaData as MakeFileBuilder.MakeFileMeta;
            var rule = meta.Rules[0];

            var commandLine = new Bam.Core.StringArray();
            commandLine.Add("-r");

            rule.AddShellCommand(System.String.Format(@"{0} {1} {2} $@ {3}",
                CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                commandLine.ToString(' '),
                newRPath,
                CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
        }
Exemple #26
0
        void IMocGenerationPolicy.Moc(
            MocGeneratedSource sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool mocCompiler,
            Bam.Core.TokenizedString generatedMocSource,
            C.HeaderFile source)
        {
            var mocOutputPath = generatedMocSource.Parse();
            var mocOutputDir = System.IO.Path.GetDirectoryName(mocOutputPath);
            if (!System.IO.Directory.Exists(mocOutputDir))
            {
                System.IO.Directory.CreateDirectory(mocOutputDir);
            }

            var args = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(args);
            args.Add(System.String.Format("-o {0}", mocOutputPath));
            args.Add(source.InputPath.Parse());
            CommandLineProcessor.Processor.Execute(context, mocCompiler, args);
        }
Exemple #27
0
        void IRccGenerationPolicy.Rcc(
            RccGeneratedSource sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool rccCompiler,
            Bam.Core.TokenizedString generatedRccSource,
            QRCFile source)
        {
            var encapsulating = sender.GetEncapsulatingReferencedModule();

            var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta;
            var target = workspace.EnsureTargetExists(encapsulating);
            var configuration = target.GetConfiguration(encapsulating);

            var output = generatedRccSource.Parse();
            var sourcePath = source.InputPath.Parse();

            var commands = new Bam.Core.StringArray();
            commands.Add(System.String.Format("[[ ! -d {0} ]] && mkdir -p {0}", System.IO.Path.GetDirectoryName(output)));

            var args = new Bam.Core.StringArray();
            args.Add(CommandLineProcessor.Processor.StringifyTool(rccCompiler));
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(args);
            args.Add(System.String.Format("-o {0}", output));
            args.Add(sourcePath);

            target.EnsureFileOfTypeExists(source.InputPath, XcodeBuilder.FileReference.EFileType.TextFile,
                                          relativePath: target.Project.GetRelativePathToProject(source.InputPath),
                                          explicitType: false);

            var rcc_commandLine = args.ToString(' ');

            commands.Add(System.String.Format("if [[ ! -e {0} || {1} -nt {0} ]]", output, sourcePath));
            commands.Add("then");
            commands.Add(System.String.Format("\techo {0}", rcc_commandLine));
            commands.Add(System.String.Format("\t{0}", rcc_commandLine));
            commands.Add("fi");

            target.AddPreBuildCommands(commands, configuration);
        }
Exemple #28
0
        void IGeneratedSourcePolicy.GenerateSource(
            GeneratedSourceModule sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool compiler,
            Bam.Core.TokenizedString generatedFilePath)
        {
            var meta = new MakeFileBuilder.MakeFileMeta(sender);
            var rule = meta.AddRule();
            rule.AddTarget(generatedFilePath);

            var buildTool = (compiler as Bam.Core.Module).MetaData as MakeFileBuilder.MakeFileMeta;
            rule.AddOrderOnlyDependency(System.String.Format("$({0})", buildTool.Rules[0].Targets[0].VariableName));

            var commandLineArgs = new Bam.Core.StringArray();
            // TODO: change this to a configuration directory really
            commandLineArgs.Add(Bam.Core.TokenizedString.Create("$(buildroot)", null).Parse());
            commandLineArgs.Add("Generated");

            var command = new System.Text.StringBuilder();
            command.AppendFormat("{0} {1} $^", compiler.Executable.ParseAndQuoteIfNecessary(), commandLineArgs.ToString(' '));
            rule.AddShellCommand(command.ToString());
        }
        IArchivingPolicy.Archive(
            StaticLibrary sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString libraryPath,
            System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> objectFiles,
            System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> headers)
        {
            var commandLine = new Bam.Core.StringArray();
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            var libraryFileDir = System.IO.Path.GetDirectoryName(libraryPath.ToString());
            if (!System.IO.Directory.Exists(libraryFileDir))
            {
                System.IO.Directory.CreateDirectory(libraryFileDir);
            }

            foreach (var input in objectFiles)
            {
                commandLine.Add(input.GeneratedPaths[C.ObjectFile.Key].ToString());
            }

            CommandLineProcessor.Processor.Execute(context, sender.Tool as Bam.Core.ICommandLineTool, commandLine);
        }
Exemple #30
0
        void IRccGenerationPolicy.Rcc(
            RccGeneratedSource sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool rccCompiler,
            Bam.Core.TokenizedString generatedRccSource,
            QRCFile source)
        {
            var meta = new MakeFileBuilder.MakeFileMeta(sender);
            var rule = meta.AddRule();
            rule.AddTarget(generatedRccSource);
            rule.AddPrerequisite(source, C.HeaderFile.Key);

            var rccOutputPath = generatedRccSource.Parse();
            var rccOutputDir = System.IO.Path.GetDirectoryName(rccOutputPath);

            var args = new Bam.Core.StringArray();
            args.Add(CommandLineProcessor.Processor.StringifyTool(rccCompiler));
            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(args);
            args.Add(System.String.Format("-o {0}", rccOutputPath));
            args.Add(source.InputPath.Parse());
            rule.AddShellCommand(args.ToString(' '));

            meta.CommonMetaData.Directories.AddUnique(rccOutputDir);
        }
Exemple #31
0
        Evaluate()
        {
            this.ReasonToExecute = null;
            var graph   = Bam.Core.Graph.Instance;
            var factory = graph.MetaData as System.Threading.Tasks.TaskFactory;

            this.EvaluationTask = factory.StartNew(() =>
            {
                // does the object file exist?
                var objectFilePath = this.GeneratedPaths[Key].Parse();
                if (!System.IO.File.Exists(objectFilePath))
                {
                    this.ReasonToExecute = Bam.Core.ExecuteReasoning.FileDoesNotExist(this.GeneratedPaths[Key]);
                    return;
                }
                var objectFileWriteTime = System.IO.File.GetLastWriteTime(objectFilePath);

                // has the source file been evaluated to be rebuilt?
                if ((this as IRequiresSourceModule).Source.ReasonToExecute != null)
                {
                    this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer(this.GeneratedPaths[Key], this.InputPath);
                    return;
                }

                // is the source file newer than the object file?
                var sourcePath      = this.InputPath.Parse();
                var sourceWriteTime = System.IO.File.GetLastWriteTime(sourcePath);
                if (sourceWriteTime > objectFileWriteTime)
                {
                    this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer(this.GeneratedPaths[Key], this.InputPath);
                    return;
                }

                if (this is WinResource)
                {
                    return;
                }

                var includeSearchPaths = (this.Settings as C.ICommonCompilerSettings).IncludePaths;

                var filesToSearch = new System.Collections.Generic.Queue <string>();
                filesToSearch.Enqueue(sourcePath);

                var headerPathsFound = new Bam.Core.StringArray();
                while (filesToSearch.Count > 0)
                {
                    var fileToSearch = filesToSearch.Dequeue();

                    string fileContents = null;
                    using (System.IO.TextReader reader = new System.IO.StreamReader(fileToSearch))
                    {
                        fileContents = reader.ReadToEnd();
                    }

                    var matches = System.Text.RegularExpressions.Regex.Matches(
                        fileContents,
                        "^\\s*#include \"(.*)\"",
                        System.Text.RegularExpressions.RegexOptions.Multiline);
                    if (0 == matches.Count)
                    {
                        // no #includes
                        return;
                    }

                    foreach (System.Text.RegularExpressions.Match match in matches)
                    {
                        bool exists = false;
                        // search for the file on the include paths the compiler uses
                        foreach (var includePath in includeSearchPaths)
                        {
                            try
                            {
                                var potentialPath = System.IO.Path.Combine(includePath.Parse(), match.Groups[1].Value);
                                if (!System.IO.File.Exists(potentialPath))
                                {
                                    continue;
                                }
                                potentialPath       = System.IO.Path.GetFullPath(potentialPath);
                                var headerWriteTime = System.IO.File.GetLastWriteTime(potentialPath);

                                // early out - header is newer than generated object file
                                if (headerWriteTime > objectFileWriteTime)
                                {
                                    this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer(
                                        this.GeneratedPaths[Key],
                                        Bam.Core.TokenizedString.CreateVerbatim(potentialPath));
                                    return;
                                }

                                if (!headerPathsFound.Contains(potentialPath))
                                {
                                    headerPathsFound.Add(potentialPath);
                                    filesToSearch.Enqueue(potentialPath);
                                }

                                exists = true;
                                break;
                            }
                            catch (System.Exception ex)
                            {
                                Bam.Core.Log.MessageAll("IncludeDependency Exception: Cannot locate '{0}' on '{1}' due to {2}", match.Groups[1].Value, includePath, ex.Message);
                            }
                        }

                        if (!exists)
                        {
#if false
                            Bam.Core.Log.DebugMessage("***** Could not locate '{0}' on any include search path, included from {1}:\n{2}",
                                                      match.Groups[1],
                                                      fileToSearch,
                                                      entry.includePaths.ToString('\n'));
#endif
                        }
                    }
                }

                return;
            });
        }
Exemple #32
0
        IDiskImagePolicy.CreateDMG(
            DiskImage sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool compiler,
            Bam.Core.TokenizedString sourceFolderPath,
            Bam.Core.TokenizedString outputPath)
        {
            var volumeNameTS = sender.CreateTokenizedString("$(OutputName)");

            lock (volumeNameTS)
            {
                if (!volumeNameTS.IsParsed)
                {
                    volumeNameTS.Parse();
                }
            }
            var volumeName            = volumeNameTS.ToString();
            var tempDiskImagePathName = System.IO.Path.GetTempPath() + System.Guid.NewGuid().ToString() + ".dmg"; // must have .dmg extension

            var commandLine = new Bam.Core.StringArray();

            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            // create the disk image
            {
                var settings = sender.Settings as IDiskImageSettings;

                var args = new Bam.Core.StringArray();
                args.Add("create");
                args.AddRange(commandLine);
                args.Add("-srcfolder");
                args.Add(System.String.Format("\"{0}\"", sourceFolderPath.ToString()));
                args.Add("-size");
                args.Add(settings.ImageSize);
                args.Add("-fs");
                args.Add("HFS+");
                args.Add("-volname");
                args.Add(System.String.Format("\"{0}\"", volumeName));
                args.Add(tempDiskImagePathName);
                CommandLineProcessor.Processor.Execute(context, compiler, args);
            }

            // mount disk image
            {
                var args = new Bam.Core.StringArray();
                args.Add("attach");
                args.AddRange(commandLine);
                args.Add(tempDiskImagePathName);
                CommandLineProcessor.Processor.Execute(context, compiler, args);
            }

            // TODO
            /// do a copy

            // unmount disk image
            {
                var args = new Bam.Core.StringArray();
                args.Add("detach");
                args.AddRange(commandLine);
                args.Add(System.String.Format("\"/Volumes/{0}\"", volumeName));
                CommandLineProcessor.Processor.Execute(context, compiler, args);
            }

            var diskImagePathName = outputPath.ToString();
            var dmgDir            = System.IO.Path.GetDirectoryName(diskImagePathName);

            Bam.Core.IOWrapper.CreateDirectoryIfNotExists(dmgDir);

            // hdiutil convert myimg.dmg -format UDZO -o myoutputimg.dmg
            // this will fail if the output DMG exists, so always write to a temporary
            // file and then move into place
            var tempDMGPath = System.IO.Path.GetTempPath() + System.Guid.NewGuid().ToString() + ".dmg";
            {
                var args = new Bam.Core.StringArray();
                args.Add("convert");
                args.AddRange(commandLine);
                args.Add(tempDiskImagePathName);
                args.Add("-format");
                args.Add("UDZO");
                args.Add("-o");
                args.Add(tempDMGPath);
                CommandLineProcessor.Processor.Execute(context, compiler, args);
            }

            // move the temporary DMG to the expected location
            {
                var args = new Bam.Core.StringArray();
                args.Add("-f");
                args.Add("-v");
                args.Add(tempDMGPath);
                args.Add(outputPath.ToStringQuoteIfNecessary()); // diskImagePathName
                CommandLineProcessor.Processor.Execute(context, Bam.Core.OSUtilities.GetInstallLocation("mv").First(), args);
            }
        }
Exemple #33
0
 CommandLineProcessor.IConvertToCommandLine.Convert(
     Bam.Core.StringArray commandLine)
 {
     CommandLineProcessor.Conversion.Convert(typeof(ClangCommon.CommandLineAssemblerImplementation), this, commandLine);
 }
Exemple #34
0
        Convert(
            this C.ICxxOnlyCompilerSettings settings,
            Bam.Core.StringArray commandLine)
        {
            if (settings.ExceptionHandler.HasValue)
            {
                switch (settings.ExceptionHandler.Value)
                {
                case C.Cxx.EExceptionHandler.Disabled:
                    commandLine.Add("-fno-exceptions");
                    break;

                case C.Cxx.EExceptionHandler.Asynchronous:
                case C.Cxx.EExceptionHandler.Synchronous:
                    commandLine.Add("-fexceptions");
                    break;

                default:
                    throw new Bam.Core.Exception("Unrecognized exception handler option, {0}", settings.ExceptionHandler.Value.ToString());
                }
            }
            if (settings.EnableRunTimeTypeInfo.HasValue)
            {
                if (settings.EnableRunTimeTypeInfo.Value)
                {
                    commandLine.Add("-frtti");
                }
                else
                {
                    commandLine.Add("-fno-rtti");
                }
            }
            if (settings.LanguageStandard.HasValue)
            {
                switch (settings.LanguageStandard.Value)
                {
                case C.Cxx.ELanguageStandard.Cxx98:
                    commandLine.Add("-std=c++98");
                    break;

                case C.Cxx.ELanguageStandard.GnuCxx98:
                    commandLine.Add("-std=gnu++98");
                    break;

                case C.Cxx.ELanguageStandard.Cxx03:
                    commandLine.Add("-std=c++03");
                    break;

                case C.Cxx.ELanguageStandard.GnuCxx03:
                    commandLine.Add("-std=gnu++03");
                    break;

                case C.Cxx.ELanguageStandard.Cxx11:
                    commandLine.Add("-std=c++11");
                    break;

                case C.Cxx.ELanguageStandard.GnuCxx11:
                    commandLine.Add("-std=gnu++11");
                    break;

                case C.Cxx.ELanguageStandard.Cxx14:
                    commandLine.Add("-std=c++14");
                    break;

                case C.Cxx.ELanguageStandard.GnuCxx14:
                    commandLine.Add("-std=gnu++14");
                    break;

                default:
                    throw new Bam.Core.Exception("Invalid C++ language standard, {0}", settings.LanguageStandard.Value.ToString());
                }
            }
        }
        Convert(
            this C.ICommonCompilerSettings settings,
            Bam.Core.StringArray commandLine)
        {
            var module = (settings as Bam.Core.Settings).Module;

            if (settings.DebugSymbols.HasValue)
            {
                if (settings.DebugSymbols.Value)
                {
                    commandLine.Add("-Z7");
                }
            }
            foreach (var warning in settings.DisableWarnings)
            {
                commandLine.Add(System.String.Format("-wd{0}", warning));
            }
            foreach (var path in settings.IncludePaths.ToEnumerableWithoutDuplicates())
            {
                commandLine.Add(System.String.Format("-I{0}", path.ToStringQuoteIfNecessary()));
            }
            if (settings.Optimization.HasValue)
            {
                switch (settings.Optimization.Value)
                {
                case C.EOptimization.Off:
                    commandLine.Add("-Od");
                    break;

                case C.EOptimization.Size:
                    commandLine.Add("-O1");
                    break;

                case C.EOptimization.Speed:
                    commandLine.Add("-O2");
                    break;

                case C.EOptimization.Custom:
                    // do nothing - deferred to compiler specific optimization settings
                    break;

                default:
                    throw new Bam.Core.Exception("Unknown optimization level, {0}", settings.Optimization.Value.ToString());
                }
            }
            if (settings.OmitFramePointer.HasValue)
            {
                commandLine.Add(settings.OmitFramePointer.Value ? "-Oy" : "-Oy-");
            }
            foreach (var define in settings.PreprocessorDefines)
            {
                if (null == define.Value)
                {
                    commandLine.Add(System.String.Format("-D{0}", define.Key));
                }
                else
                {
                    var defineValue = define.Value.ToString();
                    if (defineValue.Contains("\""))
                    {
                        defineValue = defineValue.Replace("\"", "\\\"");
                    }
                    defineValue = Bam.Core.IOWrapper.EncloseSpaceContainingPathWithDoubleQuotes(defineValue);
                    commandLine.Add(System.String.Format("-D{0}={1}", define.Key, defineValue));
                }
            }
            foreach (var undefine in settings.PreprocessorUndefines)
            {
                commandLine.Add(System.String.Format("-U{0}", undefine));
            }
            foreach (var path in settings.SystemIncludePaths.ToEnumerableWithoutDuplicates())
            {
                commandLine.Add(System.String.Format("-I{0}", path.ToStringQuoteIfNecessary()));
            }
            if (settings.TargetLanguage.HasValue)
            {
                switch (settings.TargetLanguage.Value)
                {
                case C.ETargetLanguage.C:
                    commandLine.Add("-TC");
                    break;

                case C.ETargetLanguage.Cxx:
                    commandLine.Add("-TP");
                    break;

                default:
                    throw new Bam.Core.Exception("Unsupported target language, {0}", settings.TargetLanguage.Value.ToString());
                }
            }
            if (settings.WarningsAsErrors.HasValue)
            {
                if (settings.WarningsAsErrors.Value)
                {
                    commandLine.Add("-WX");
                }
                else
                {
                    commandLine.Add("-WX-");
                }
            }
            if (settings.OutputType.HasValue)
            {
                switch (settings.OutputType.Value)
                {
                case C.ECompilerOutput.CompileOnly:
                    commandLine.Add(System.String.Format("-c -Fo{0}", module.GeneratedPaths[C.ObjectFile.Key].ToStringQuoteIfNecessary()));
                    break;

                case C.ECompilerOutput.Preprocess:
                    commandLine.Add(System.String.Format("-E -Fo{0}", module.GeneratedPaths[C.ObjectFile.Key].ToStringQuoteIfNecessary()));
                    break;

                default:
                    throw new Bam.Core.Exception("Unknown output type, {0}", settings.OutputType.Value.ToString());
                }
            }
            foreach (var header in settings.NamedHeaders)
            {
                commandLine.Add(System.String.Format("-FI{0}", header));
            }
        }
        IDiskImagePolicy.CreateDMG(
            DiskImage sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool compiler,
            Bam.Core.TokenizedString sourceFolderPath,
            Bam.Core.TokenizedString outputPath)
        {
            var volumeName            = sender.CreateTokenizedString("$(OutputName)").Parse();
            var tempDiskImagePathName = System.IO.Path.GetTempPath() + System.Guid.NewGuid().ToString() + ".dmg"; // must have .dmg extension
            var diskImagePathName     = outputPath.ToString();

            var commandLine = new Bam.Core.StringArray();

            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            // create the disk image
            {
                var settings = sender.Settings as IDiskImageSettings;

                var args = new Bam.Core.StringArray();
                args.Add("create");
                args.AddRange(commandLine);
                args.Add("-srcfolder");
                args.Add(System.String.Format("\"{0}\"", sourceFolderPath.ToString()));
                args.Add("-size");
                args.Add(settings.ImageSize);
                args.Add("-fs");
                args.Add("HFS+");
                args.Add("-volname");
                args.Add(System.String.Format("\"{0}\"", volumeName));
                args.Add(tempDiskImagePathName);
                CommandLineProcessor.Processor.Execute(context, compiler, args);
            }

            // mount disk image
            {
                var args = new Bam.Core.StringArray();
                args.Add("attach");
                args.AddRange(commandLine);
                args.Add(tempDiskImagePathName);
                CommandLineProcessor.Processor.Execute(context, compiler, args);
            }

            // TODO
            /// do a copy

            // unmount disk image
            {
                var args = new Bam.Core.StringArray();
                args.Add("detach");
                args.AddRange(commandLine);
                args.Add(System.String.Format("\"/Volumes/{0}\"", volumeName));
                CommandLineProcessor.Processor.Execute(context, compiler, args);
            }

            var dmgDir = System.IO.Path.GetDirectoryName(diskImagePathName);

            if (!System.IO.Directory.Exists(dmgDir))
            {
                System.IO.Directory.CreateDirectory(dmgDir);
            }

            // hdiutil convert myimg.dmg -format UDZO -o myoutputimg.dmg
            {
                var args = new Bam.Core.StringArray();
                args.Add("convert");
                args.AddRange(commandLine);
                args.Add(tempDiskImagePathName);
                args.Add("-format");
                args.Add("UDZO");
                args.Add("-o");
                args.Add(diskImagePathName);
                CommandLineProcessor.Processor.Execute(context, compiler, args);
            }
        }
        IExternalSourceGeneratorPolicy.GenerateSource(
            ExternalSourceGenerator sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString executable,
            Bam.Core.TokenizedStringArray arguments,
            Bam.Core.TokenizedString output_directory,
            System.Collections.Generic.IReadOnlyDictionary <string, Bam.Core.TokenizedString> expected_output_files,
            System.Collections.Generic.IReadOnlyDictionary <string, Bam.Core.TokenizedString> input_files
            )
        {
            var encapsulating = sender.GetEncapsulatingReferencedModule();

            var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta;
            var target    = workspace.EnsureTargetExists(encapsulating);

            if (encapsulating == sender)
            {
                target.SetType(XcodeBuilder.Target.EProductType.Utility);
            }
            var configuration = target.GetConfiguration(encapsulating);

            if (encapsulating == sender)
            {
                configuration.SetProductName(Bam.Core.TokenizedString.CreateVerbatim("${TARGET_NAME}"));
            }

            var commands = new Bam.Core.StringArray();

            commands.Add(
                System.String.Format(
                    "[[ ! -d {0} ]] && mkdir -p {0}",
                    Bam.Core.IOWrapper.EscapeSpacesInPath(output_directory.ToString())
                    )
                );

            var condition_text = new System.Text.StringBuilder();

            condition_text.Append("if [[ ");
            var last_output = expected_output_files.Values.Last();

            foreach (var output in expected_output_files.Values)
            {
                var output_path = Bam.Core.IOWrapper.EscapeSpacesInPath(output.ToString());
                condition_text.AppendFormat("! -e {0} ", output_path);
                foreach (var input in input_files.Values)
                {
                    var input_path = Bam.Core.IOWrapper.EscapeSpacesInPath(input.ToString());
                    condition_text.AppendFormat("|| {1} -nt {0} ", output_path, input_path);
                }
                if (output != last_output)
                {
                    condition_text.AppendFormat("|| ");
                }
            }
            condition_text.AppendLine("]]");
            condition_text.AppendLine("then");

            var cmd_line = System.String.Format("{0} {1}", executable.ToStringQuoteIfNecessary(), arguments.ToString(' '));

            condition_text.AppendLine(System.String.Format("\techo {0}", cmd_line));
            condition_text.AppendLine(System.String.Format("\t{0}", cmd_line));
            condition_text.AppendLine("fi");
            commands.Add(condition_text.ToString());

            target.AddPreBuildCommands(commands, configuration);
        }
Exemple #38
0
        Convert(
            this C.ICommonAssemblerSettings settings,
            Bam.Core.StringArray commandLine)
        {
            var module = (settings as Bam.Core.Settings).Module;

            switch (settings.Bits.Value)
            {
            case C.EBit.SixtyFour:
                commandLine.Add("-arch x86_64");
                break;

            case C.EBit.ThirtyTwo:
                commandLine.Add("-arch i386");
                break;

            default:
                throw new Bam.Core.Exception("Unknown bit depth, {0}", settings.Bits.Value);
            }
            if (settings.DebugSymbols)
            {
                commandLine.Add("-g");
            }
            switch (settings.OutputType)
            {
            case C.ECompilerOutput.CompileOnly:
                commandLine.Add(System.String.Format("-c -o {0}", module.GeneratedPaths[C.ObjectFile.Key].ToStringQuoteIfNecessary()));
                break;

            case C.ECompilerOutput.Preprocess:
                commandLine.Add(System.String.Format("-E -o {0}", module.GeneratedPaths[C.ObjectFile.Key].ToStringQuoteIfNecessary()));
                break;

            default:
                throw new Bam.Core.Exception("Unknown output type, {0}", settings.OutputType.ToString());
            }
            if (settings.WarningsAsErrors)
            {
                commandLine.Add("-Werror");
            }
            else
            {
                commandLine.Add("-Wno-error");
            }
            foreach (var path in settings.IncludePaths.ToEnumerableWithoutDuplicates())
            {
                commandLine.Add(System.String.Format("-I{0}", path.ToStringQuoteIfNecessary()));
            }
            foreach (var define in settings.PreprocessorDefines)
            {
                if (null == define.Value)
                {
                    commandLine.Add(System.String.Format("-D{0}", define.Key));
                }
                else
                {
                    var defineValue = define.Value.ToString();
                    if (defineValue.Contains("\""))
                    {
                        defineValue = defineValue.Replace("\"", "\\\"");
                    }
                    defineValue = Bam.Core.IOWrapper.EncloseSpaceContainingPathWithDoubleQuotes(defineValue);
                    commandLine.Add(System.String.Format("-D{0}={1}", define.Key, defineValue));
                }
            }
        }
Exemple #39
0
        public static void PostExecution()
        {
            var graph      = Bam.Core.Graph.Instance;
            var commonMeta = graph.MetaData as MakeFileCommonMetaData;

            var makeEnvironment = new System.Text.StringBuilder();
            var makeVariables   = new System.Text.StringBuilder();
            var makeRules       = new System.Text.StringBuilder();

            // delete suffix rules
            makeEnvironment.AppendLine(".SUFFIXES:");

            commonMeta.ExportEnvironment(makeEnvironment);
            commonMeta.ExportDirectories(makeVariables);

            // all rule
            var prerequisitesOfTargetAll = new Bam.Core.StringArray();

            // loop over all metadata, until the top-most modules with Make metadata are added to 'all'
            // this allows skipping over any upper modules without Make policies
            foreach (var metadata in allMeta)
            {
                foreach (var rule in metadata.Rules)
                {
                    rule.AppendAllPrerequisiteTargetNames(prerequisitesOfTargetAll);
                }
            }
            makeRules.Append("all:");
            makeRules.AppendLine(prerequisitesOfTargetAll.ToString(' '));

            // directory direction rule
            makeRules.AppendLine("$(DIRS):");
            if (Bam.Core.OSUtilities.IsWindowsHosting)
            {
                makeRules.AppendLine("\tmkdir $@");
            }
            else
            {
                makeRules.AppendLine("\tmkdir -pv $@");
            }

            // clean rule
            makeRules.AppendLine(".PHONY: clean");
            makeRules.AppendLine("clean:");
            if (Bam.Core.OSUtilities.IsWindowsHosting)
            {
                makeRules.AppendLine("\t-cmd.exe /C RMDIR /S /Q $(DIRS)");
            }
            else
            {
                makeRules.AppendLine("\t@rm -frv $(DIRS)");
            }

            // write all variables and rules
            foreach (var metadata in allMeta)
            {
                foreach (var rule in metadata.Rules)
                {
                    rule.WriteVariables(makeVariables);
                    rule.WriteRules(makeRules);
                }
            }

            Bam.Core.Log.DebugMessage("MAKEFILE CONTENTS: BEGIN");
            Bam.Core.Log.DebugMessage(makeEnvironment.ToString());
            Bam.Core.Log.DebugMessage(makeVariables.ToString());
            Bam.Core.Log.DebugMessage(makeRules.ToString());
            Bam.Core.Log.DebugMessage("MAKEFILE CONTENTS: END");

            var makeFilePath = Bam.Core.TokenizedString.Create("$(buildroot)/Makefile", null);

            makeFilePath.Parse();

            using (var writer = new System.IO.StreamWriter(makeFilePath.ToString()))
            {
                writer.Write(makeEnvironment.ToString());
                writer.Write(makeVariables.ToString());
                writer.Write(makeRules.ToString());
            }

            Bam.Core.Log.Info("Successfully created MakeFile for package '{0}'\n\t{1}", graph.MasterPackage.Name, makeFilePath);
        }
        execute_vcvars(
            C.EBit depth,
            bool has64bithost_32bitcross,
            bool hasNative64BitTools,
            Bam.Core.StringArray inherited_envvars,
            System.Collections.Generic.Dictionary <string, Bam.Core.StringArray> required_envvars
            )
        {
            var startinfo = new System.Diagnostics.ProcessStartInfo();

            startinfo.FileName = @"c:\Windows\System32\cmd.exe";
            startinfo.EnvironmentVariables.Clear();
            if (null != inherited_envvars)
            {
                foreach (var inherited in inherited_envvars)
                {
                    startinfo.EnvironmentVariables.Add(inherited, System.Environment.GetEnvironmentVariable(inherited));
                }
            }
            if (null != required_envvars)
            {
                foreach (System.Collections.Generic.KeyValuePair <string, Bam.Core.StringArray> required in required_envvars)
                {
                    if (startinfo.EnvironmentVariables.ContainsKey(required.Key))
                    {
                        var existing_value = startinfo.EnvironmentVariables[required.Key];
                        var updated_value  = System.String.Format(
                            "{0};{1}",
                            System.Environment.ExpandEnvironmentVariables(required.Value.ToString(';')),
                            existing_value
                            );
                        startinfo.EnvironmentVariables[required.Key] = updated_value;
                    }
                    else
                    {
                        startinfo.EnvironmentVariables.Add(required.Key, System.Environment.ExpandEnvironmentVariables(required.Value.ToString(';')));
                    }
                }
            }
            startinfo.UseShellExecute        = false;
            startinfo.RedirectStandardInput  = true;
            startinfo.RedirectStandardOutput = true;
            startinfo.RedirectStandardError  = true;

            System.Func <string> vcvarsall_command = () =>
            {
                var command_and_args = new System.Text.StringBuilder();
                command_and_args.Append("vcvarsall.bat ");
                switch (depth)
                {
                case C.EBit.ThirtyTwo:
                {
                    if (Bam.Core.OSUtilities.Is64BitHosting && has64bithost_32bitcross)
                    {
                        command_and_args.Append("amd64_x86 ");
                    }
                    else
                    {
                        command_and_args.Append("x86 ");
                    }
                }
                break;

                case C.EBit.SixtyFour:
                {
                    if (Bam.Core.OSUtilities.Is64BitHosting && hasNative64BitTools)
                    {
                        command_and_args.Append("amd64 ");
                    }
                    else
                    {
                        command_and_args.Append("x86_amd64 ");
                    }
                }
                break;
                }
                // VisualC packages define their 'default' WindowsSDK package to function with
                // if this is different to what is being used, append the version fo the vcvarsall.bat command
                var visualC = Bam.Core.Graph.Instance.Packages.First(item => item.Name == "VisualC");
                var defaultWindowsSDKVersion = visualC.Dependents.First(item => item.Item1 == "WindowsSDK").Item2;
                var windowsSDK = Bam.Core.Graph.Instance.Packages.FirstOrDefault(item => item.Name == "WindowsSDK");
                if (null != windowsSDK)
                {
                    if (windowsSDK.Version != defaultWindowsSDKVersion)
                    {
                        command_and_args.Append(System.String.Format("{0} ", windowsSDK.Version));
                    }
                    else
                    {
                        var option_type = System.Type.GetType("WindowsSDK.Options.WindowsSDK10Version", throwOnError: false);
                        if (null != option_type)
                        {
                            var option_type_instance = System.Activator.CreateInstance(option_type) as Bam.Core.IStringCommandLineArgument;
                            if (null != option_type_instance)
                            {
                                var win10Option = Bam.Core.CommandLineProcessor.Evaluate(option_type_instance);
                                if (null != win10Option)
                                {
                                    command_and_args.Append(System.String.Format("{0} ", win10Option));
                                }
                            }
                        }
                    }
                }
                return(command_and_args.ToString());
            };

            var environment_generator_cmdline = System.String.Empty;
            // allow the WindowsSDK to provide an alternative mechanism for generating
            // and environment in which to execute VisualC and WindowsSDK tools
            var windowssdk_meta = Bam.Core.Graph.Instance.PackageMetaData <WindowsSDK.MetaData>("WindowsSDK");

            if (windowssdk_meta.Contains("setenvdir") && windowssdk_meta.Contains("setenvcmd"))
            {
                startinfo.WorkingDirectory    = windowssdk_meta["setenvdir"] as string;
                environment_generator_cmdline = windowssdk_meta["setenvcmd"] as string;
                switch (depth)
                {
                case C.EBit.ThirtyTwo:
                    environment_generator_cmdline += " /x86";
                    break;

                case C.EBit.SixtyFour:
                    environment_generator_cmdline += " /x64";
                    break;
                }
            }
            else
            {
                startinfo.WorkingDirectory    = System.IO.Path.Combine(this.InstallDir.ToString(), subpath_to_vcvars);
                environment_generator_cmdline = vcvarsall_command();
            }

            // allow the WindowsSDK to override the VisualStudio project's PlatformToolset
            if (windowssdk_meta.Contains("PlatformToolset"))
            {
                var vc_meta = Bam.Core.Graph.Instance.PackageMetaData <VisualC.MetaData>("VisualC");
                vc_meta.PlatformToolset = windowssdk_meta["PlatformToolset"] as string;
            }

            var arguments = new System.Text.StringBuilder();

            arguments.AppendFormat("/C {0} && SET", environment_generator_cmdline);
            startinfo.Arguments = arguments.ToString();

            var process = new System.Diagnostics.Process();

            process.StartInfo = startinfo;

            // if you don't async read the output, then the process will never finish
            // as the buffer is filled up
            // EOLs will also be trimmed from these, so always append whole lines
            var stdout = new System.Text.StringBuilder();

            process.OutputDataReceived += (sender, args) => stdout.AppendLine(args.Data);
            var stderr = new System.Text.StringBuilder();

            process.ErrorDataReceived += (sender, args) => stderr.AppendLine(args.Data);

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.StandardInput.Close();
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                throw new Bam.Core.Exception("{0} failed: {1}", environment_generator_cmdline, stderr.ToString());
            }

            var env   = new System.Collections.Generic.Dictionary <string, Bam.Core.TokenizedStringArray>();
            var lines = stdout.ToString().Split(
                new[] { System.Environment.NewLine },
                System.StringSplitOptions.RemoveEmptyEntries
                );

            foreach (var line in lines)
            {
                Bam.Core.Log.DebugMessage("{0}->{1}", environment_generator_cmdline, line);
                var equals_index = line.IndexOf('=');
                if (-1 == equals_index)
                {
                    continue;
                }
                var key   = line.Remove(equals_index);
                var value = line.Remove(0, equals_index + 1);
                if (System.String.IsNullOrEmpty(key) || System.String.IsNullOrEmpty(value))
                {
                    continue;
                }
                var splitValue = value.Split(new[] { ';' });
                var valueArray = new Bam.Core.TokenizedStringArray();
                foreach (var v in splitValue)
                {
                    valueArray.Add(Bam.Core.TokenizedString.CreateVerbatim(v));
                }
                env.Add(key, valueArray);
            }
            Bam.Core.Log.Info(@"Generating {0}-bit build environment using '{1}\{2}'",
                              (int)depth,
                              startinfo.WorkingDirectory,
                              environment_generator_cmdline.TrimEnd()
                              );
            foreach (System.Collections.Generic.KeyValuePair <string, Bam.Core.TokenizedStringArray> entry in env)
            {
                Bam.Core.Log.DebugMessage("\t{0} = {1}", entry.Key, entry.Value.ToString(';'));
            }
            return(env);
        }
        IArchivingPolicy.Archive(
            StaticLibrary sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString libraryPath,
            System.Collections.ObjectModel.ReadOnlyCollection <Bam.Core.Module> objectFiles,
            System.Collections.ObjectModel.ReadOnlyCollection <Bam.Core.Module> headers)
        {
            if (0 == objectFiles.Count)
            {
                return;
            }

            var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta;
            var target    = workspace.EnsureTargetExists(sender);

            target.EnsureOutputFileReferenceExists(
                sender.CreateTokenizedString("@filename($(0))", libraryPath),
                XcodeBuilder.FileReference.EFileType.Archive,
                XcodeBuilder.Target.EProductType.StaticLibrary);
            var configuration = target.GetConfiguration(sender);

            if (sender.Macros["OutputName"].Equals(sender.Macros["modulename"]))
            {
                configuration.SetProductName(Bam.Core.TokenizedString.CreateVerbatim("${TARGET_NAME}"));
            }
            else
            {
                configuration.SetProductName(sender.Macros["OutputName"]);
            }

            foreach (var header in headers)
            {
                target.EnsureHeaderFileExists((header as HeaderFile).InputPath);
            }

            var excludedSource  = new XcodeBuilder.MultiConfigurationValue();
            var realObjectFiles = objectFiles.Where(item => !(item is AssembledObjectFile)); // C,C++,ObjC,ObjC++

            if (realObjectFiles.Any())
            {
                var xcodeConvertParameterTypes = new Bam.Core.TypeArray
                {
                    typeof(Bam.Core.Module),
                    typeof(XcodeBuilder.Configuration)
                };

                var sharedSettings = C.SettingsBase.SharedSettings(
                    realObjectFiles,
                    typeof(ClangCommon.XcodeCompilerImplementation),
                    typeof(XcodeProjectProcessor.IConvertToProject),
                    xcodeConvertParameterTypes);
                XcodeSharedSettings.Tweak(sharedSettings);
                (sharedSettings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration);

                foreach (var objFile in realObjectFiles)
                {
                    if (!(objFile as C.ObjectFileBase).PerformCompilation)
                    {
                        var fullPath = (objFile as C.ObjectFileBase).InputPath.Parse();
                        var filename = System.IO.Path.GetFileName(fullPath);
                        excludedSource.Add(filename);
                    }

                    var buildFile     = objFile.MetaData as XcodeBuilder.BuildFile;
                    var deltaSettings = (objFile.Settings as C.SettingsBase).CreateDeltaSettings(sharedSettings, objFile);
                    if (null != deltaSettings)
                    {
                        var commandLine = new Bam.Core.StringArray();
                        (deltaSettings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);
                        if (commandLine.Count > 0)
                        {
                            // Cannot set per-file-per-configuration settings, so blend them together
                            if (null == buildFile.Settings)
                            {
                                buildFile.Settings = commandLine;
                            }
                            else
                            {
                                buildFile.Settings.AddRangeUnique(commandLine);
                            }
                        }
                    }
                    configuration.BuildFiles.Add(buildFile);
                }

                // now deal with other object file types
                var assembledObjectFiles = objectFiles.Where(item => item is AssembledObjectFile);
                foreach (var asmObj in assembledObjectFiles)
                {
                    var buildFile = asmObj.MetaData as XcodeBuilder.BuildFile;
                    configuration.BuildFiles.Add(buildFile);
                }
            }
            else
            {
                (objectFiles[0].Settings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration);
                foreach (var objFile in objectFiles)
                {
                    if (!(objFile as C.ObjectFileBase).PerformCompilation)
                    {
                        var fullPath = (objFile as C.ObjectFileBase).InputPath.Parse();
                        var filename = System.IO.Path.GetFileName(fullPath);
                        excludedSource.Add(filename);
                    }

                    var buildFile = objFile.MetaData as XcodeBuilder.BuildFile;
                    configuration.BuildFiles.Add(buildFile);
                }
            }

            configuration["EXCLUDED_SOURCE_FILE_NAMES"] = excludedSource;

            // convert librarian settings to the Xcode project
            if (sender.Settings is XcodeProjectProcessor.IConvertToProject)
            {
                (sender.Settings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration);
            }

            // order only dependents
            foreach (var required in sender.Requirements)
            {
                if (null == required.MetaData)
                {
                    continue;
                }
                if (required is HeaderLibrary)
                {
                    // the target for a HeaderLibrary has no FileReference output, and thus cannot be an order only dependency
                    continue;
                }

                var requiredTarget = required.MetaData as XcodeBuilder.Target;
                if (null != requiredTarget)
                {
                    target.Requires(requiredTarget);
                }
            }
            // any non-C module targets should be order-only dependencies
            // note: this is unlikely to happen, as StaticLibraries don't have hard 'dependencies'
            // because there is no fixed 'link' action at the end
            foreach (var dependent in sender.Dependents)
            {
                if (null == dependent.MetaData)
                {
                    continue;
                }
                if (dependent is C.CModule)
                {
                    continue;
                }
                var dependentTarget = dependent.MetaData as XcodeBuilder.Target;
                if (null != dependentTarget)
                {
                    target.Requires(dependentTarget);
                }
            }
            // however, there may be forwarded libraries, and these are useful order only dependents
            foreach (var dependent in (sender as IForwardedLibraries).ForwardedLibraries)
            {
                if (null == dependent.MetaData)
                {
                    continue;
                }
                var dependentTarget = dependent.MetaData as XcodeBuilder.Target;
                if (null != dependentTarget)
                {
                    target.Requires(dependentTarget);
                }
            }
        }
        Convert(
            this C.ICxxOnlyCompilerSettings settings,
            Bam.Core.StringArray commandLine)
        {
            if (settings.ExceptionHandler.HasValue)
            {
                switch (settings.ExceptionHandler.Value)
                {
                case C.Cxx.EExceptionHandler.Disabled:
                    commandLine.Add("-fno-exceptions");
                    break;

                case C.Cxx.EExceptionHandler.Asynchronous:
                case C.Cxx.EExceptionHandler.Synchronous:
                    commandLine.Add("-fexceptions");
                    break;

                default:
                    throw new Bam.Core.Exception("Unrecognized exception handler option, {0}", settings.ExceptionHandler.Value.ToString());
                }
            }
            if (settings.LanguageStandard.HasValue)
            {
                switch (settings.LanguageStandard.Value)
                {
                case C.Cxx.ELanguageStandard.Cxx98:
                    commandLine.Add("-std=c++98");
                    break;

                case C.Cxx.ELanguageStandard.GnuCxx98:
                    commandLine.Add("-std=gnu++98");
                    break;

                case C.Cxx.ELanguageStandard.Cxx11:
                    commandLine.Add("-std=c++11");
                    break;

                default:
                    throw new Bam.Core.Exception("Invalid C++ language standard, {0}", settings.LanguageStandard.Value.ToString());
                }
            }
            if (settings.StandardLibrary.HasValue)
            {
                switch (settings.StandardLibrary.Value)
                {
                case C.Cxx.EStandardLibrary.NotSet:
                    break;

                case C.Cxx.EStandardLibrary.libstdcxx:
                    commandLine.Add("-stdlib=libstdc++");
                    break;

                case C.Cxx.EStandardLibrary.libcxx:
                    commandLine.Add("-stdlib=libc++");
                    break;

                default:
                    throw new Bam.Core.Exception("Invalid C++ standard library {0}", settings.StandardLibrary.Value.ToString());
                }
            }
        }
Exemple #43
0
        public static void PostExecution()
        {
            var graph      = Bam.Core.Graph.Instance;
            var commonMeta = graph.MetaData as MakeFileCommonMetaData;

            var makeEnvironment = new System.Text.StringBuilder();
            var makeVariables   = new System.Text.StringBuilder();
            var makeRules       = new System.Text.StringBuilder();

            // delete suffix rules
            makeEnvironment.AppendLine(".SUFFIXES:");
            foreach (var env in commonMeta.Environment)
            {
                makeEnvironment.AppendFormat("{0}:={1}", env.Key, env.Value.ToString(System.IO.Path.PathSeparator));
                makeEnvironment.AppendLine();
            }

            if (commonMeta.Directories.Count > 0)
            {
                makeVariables.Append("DIRS:=");
                foreach (var dir in commonMeta.Directories)
                {
                    makeVariables.AppendFormat("{0} ", dir);
                }
                makeVariables.AppendLine();
            }

            // all rule
            makeRules.Append("all:");
            var allPrerequisites = new Bam.Core.StringArray();

            // loop over all ranks, until the top-most modules with Make metadata are added to 'all'
            // this allows skipping over any upper modules without Make policies
            foreach (var rank in graph)
            {
                foreach (var module in rank)
                {
                    var metadata = module.MetaData as MakeFileMeta;
                    if (null == metadata)
                    {
                        continue;
                    }
                    foreach (var rule in metadata.Rules)
                    {
                        // TODO: could just exit from the loop after the first iteration
                        if (!rule.IsFirstRule)
                        {
                            continue;
                        }
                        rule.AppendTargetNames(allPrerequisites);
                    }
                }
                if (allPrerequisites.Any())
                {
                    break;
                }
            }
            makeRules.AppendLine(allPrerequisites.ToString(' '));

            // directory direction rule
            makeRules.AppendLine("$(DIRS):");
            if (Bam.Core.OSUtilities.IsWindowsHosting)
            {
                makeRules.AppendLine("\tmkdir $@");
            }
            else
            {
                makeRules.AppendLine("\tmkdir -pv $@");
            }

            // clean rule
            makeRules.AppendLine(".PHONY: clean");
            makeRules.AppendLine("clean:");
            makeRules.AppendLine("\t@rm -frv $(DIRS)");

            foreach (var rank in graph.Reverse())
            {
                foreach (var module in rank)
                {
                    var metadata = module.MetaData as MakeFileMeta;
                    if (null == metadata)
                    {
                        continue;
                    }

                    foreach (var rule in metadata.Rules)
                    {
                        rule.WriteVariables(makeVariables);
                        rule.WriteRules(makeRules);
                    }
                }
            }

            Bam.Core.Log.DebugMessage("MAKEFILE CONTENTS: BEGIN");
            Bam.Core.Log.DebugMessage(makeEnvironment.ToString());
            Bam.Core.Log.DebugMessage(makeVariables.ToString());
            Bam.Core.Log.DebugMessage(makeRules.ToString());
            Bam.Core.Log.DebugMessage("MAKEFILE CONTENTS: END");

            var makeFilePath = Bam.Core.TokenizedString.Create("$(buildroot)/Makefile", null);

            makeFilePath.Parse();

            using (var writer = new System.IO.StreamWriter(makeFilePath.ToString()))
            {
                writer.Write(makeEnvironment.ToString());
                writer.Write(makeVariables.ToString());
                writer.Write(makeRules.ToString());
            }

            Bam.Core.Log.Info("Successfully created MakeFile for package '{0}'\n\t{1}", graph.MasterPackage.Name, makeFilePath);
        }
Exemple #44
0
        Build(
            XmlUtilities.XmlModule moduleToBuild,
            out bool success)
        {
            var isPlist       = moduleToBuild is XmlUtilities.OSXPlistModule;
            var locationMap   = moduleToBuild.Locations;
            var outputDir     = locationMap[XmlUtilities.OSXPlistModule.OutputDir];
            var outputDirPath = outputDir.GetSingleRawPath();

            if (!System.IO.Directory.Exists(outputDirPath))
            {
                System.IO.Directory.CreateDirectory(outputDirPath);
            }

            var xmlFileLoc  = locationMap[XmlUtilities.XmlModule.OutputFile];
            var xmlFilePath = xmlFileLoc.GetSingleRawPath();

            // write a script that can be invoked by the MakeFile to generate the XML file
            var shellScriptLeafName = isPlist ? "writePList.py" : "writeXMLFile.py";
            var shellScriptLoc      = Bam.Core.FileLocation.Get(outputDir, shellScriptLeafName, Bam.Core.Location.EExists.WillExist);
            var shellScriptPath     = shellScriptLoc.GetSingleRawPath();

            XmlUtilities.XmlDocumentToPythonScript.Write(moduleToBuild.Document, shellScriptPath, xmlFilePath);

            var node     = moduleToBuild.OwningNode;
            var makeFile = new MakeFile(node, this.topLevelMakeFilePath);

            var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist);

            var recipe = new Bam.Core.StringArray();

            recipe.Add(System.String.Format("$(shell python {0})", shellScriptPath));

            var rule = new MakeFileRule(
                moduleToBuild,
                XmlUtilities.XmlModule.OutputFile,
                node.UniqueModuleName,
                dirsToCreate,
                null,
                null,
                recipe);

            rule.OutputLocationKeys = new Bam.Core.Array <Bam.Core.LocationKey>(XmlUtilities.XmlModule.OutputFile);
            makeFile.RuleArray.Add(rule);

            var makeFilePath = MakeFileBuilder.GetMakeFilePathName(node);

            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(makeFilePath));

            using (var makeFileWriter = new System.IO.StreamWriter(makeFilePath))
            {
                makeFile.Write(makeFileWriter);
            }

            var exportedTargets   = makeFile.ExportedTargets;
            var exportedVariables = makeFile.ExportedVariables;
            var returnData        = new MakeFileData(makeFilePath, exportedTargets, exportedVariables, null);

            success = true;
            return(returnData);
        }
Exemple #45
0
 Convert(
     this ICommonAssemblerSettings settings,
     Bam.Core.StringArray commandLine)
 {
 }
 Convert(
     this C.IObjectiveCxxOnlyCompilerSettings settings,
     Bam.Core.StringArray commandLine)
 {
 }
Exemple #47
0
        Serialize(
            string solutionPath)
        {
            var ProjectTypeGuid    = System.Guid.Parse("8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942");
            var SolutionFolderGuid = System.Guid.Parse("2150E333-8FDC-42A3-9474-1A3956D46DE8");

            var content = new System.Text.StringBuilder();

            var visualCMeta = Bam.Core.Graph.Instance.PackageMetaData <VisualC.MetaData>("VisualC");

            content.AppendFormat(@"Microsoft Visual Studio Solution File, Format Version {0}", visualCMeta.SolutionFormatVersion);
            content.AppendLine();

            var configs = new Bam.Core.StringArray();

            foreach (var project in this.Projects)
            {
                var relativeProjectPath = Bam.Core.RelativePathUtilities.GetPath(project.ProjectPath, solutionPath);
                content.AppendFormat("Project(\"{0}\") = \"{1}\", \"{2}\", \"{3}\"",
                                     ProjectTypeGuid.ToString("B").ToUpper(),
                                     System.IO.Path.GetFileNameWithoutExtension(project.ProjectPath),
                                     relativeProjectPath,
                                     project.GuidString);
                content.AppendLine();
                content.AppendLine("EndProject");

                foreach (var config in project.Configurations)
                {
                    configs.AddUnique(config.Value.FullName);
                }
            }
            foreach (var folder in this.SolutionFolders)
            {
                var folderPath = folder.Value.Path;
                var folderGuid = folder.Value.GuidString;
                content.AppendFormat("Project(\"{0}\") = \"{1}\", \"{2}\", \"{3}\"",
                                     SolutionFolderGuid.ToString("B").ToUpper(),
                                     folderPath,
                                     folderPath,
                                     folderGuid);
                content.AppendLine();
                content.AppendLine("EndProject");
            }
            content.AppendLine("Global");
            content.AppendLine("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
            foreach (var config in configs)
            {
                // TODO: I'm sure these are not meant to be identical, but I don't know what else to put here
                content.AppendFormat("\t\t{0} = {0}", config);
                content.AppendLine();
            }
            content.AppendLine("\tEndGlobalSection");
            content.AppendLine("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");
            foreach (var project in this.Projects)
            {
                var guid = project.GuidString;
                var thisProjectConfigs = new Bam.Core.StringArray();

                // write the configurations for which build steps have been defined
                foreach (var config in project.Configurations)
                {
                    var configName = config.Value.FullName;
                    content.AppendFormat("\t\t{0}.{1}.ActiveCfg = {1}", guid, configName);
                    content.AppendLine();
                    content.AppendFormat("\t\t{0}.{1}.Build.0 = {1}", guid, configName);
                    content.AppendLine();
                    thisProjectConfigs.AddUnique(configName);
                }

                // now cater for any configurations that the project does not support
                var unsupportedConfigs = configs.Complement(thisProjectConfigs) as Bam.Core.StringArray;
                foreach (var uConfig in unsupportedConfigs)
                {
                    // a missing "XX.YY.Build.0" line means not configured to build
                    // also, the remapping between config names seems a little arbitrary, but seems to work
                    // might be related to the project not having an ProjectConfiguration for the unsupported config
                    content.AppendFormat("\t\t{0}.{1}.ActiveCfg = {2}", guid, uConfig, thisProjectConfigs[0]);
                    content.AppendLine();
                }
            }
            content.AppendLine("\tEndGlobalSection");
            content.AppendLine("\tGlobalSection(SolutionProperties) = preSolution");
            content.AppendLine("\t\tHideSolutionNode = FALSE");
            content.AppendLine("\tEndGlobalSection");
            if (this.SolutionFolders.Count() > 0)
            {
                content.AppendLine("\tGlobalSection(NestedProjects) = preSolution");
                foreach (var folder in this.SolutionFolders)
                {
                    foreach (var nested in folder.Value.NestedEntities)
                    {
                        content.AppendFormat("\t\t{0} = {1}", nested.GuidString, folder.Value.GuidString);
                        content.AppendLine();
                    }
                }
                content.AppendLine("\tEndGlobalSection");
            }
            content.AppendLine("EndGlobal");

            return(content);
        }
        DetermineSpecs(
            Bam.Core.BaseTarget baseTarget,
            Bam.Core.IToolset toolset)
        {
            // get version
            string gccVersion = null;
            {
                var processStartInfo = new System.Diagnostics.ProcessStartInfo();
                processStartInfo.FileName               = toolset.Tool(typeof(C.ICompilerTool)).Executable(baseTarget);
                processStartInfo.ErrorDialog            = true;
                processStartInfo.UseShellExecute        = false;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.Arguments              = "-dumpversion";

                System.Diagnostics.Process process = null;
                try
                {
                    process = System.Diagnostics.Process.Start(processStartInfo);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    throw new Bam.Core.Exception("'{0}': process filename '{1}'", ex.Message, processStartInfo.FileName);
                }

                if (null == process)
                {
                    throw new Bam.Core.Exception("Unable to execute '{0}'", processStartInfo.FileName);
                }

                gccVersion = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                gccVersion = gccVersion.Trim();
            }

            // get target
            string gccTarget = null;
            {
                var processStartInfo = new System.Diagnostics.ProcessStartInfo();
                processStartInfo.FileName               = toolset.Tool(typeof(C.ICompilerTool)).Executable(baseTarget);
                processStartInfo.ErrorDialog            = true;
                processStartInfo.UseShellExecute        = false;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.Arguments              = "-dumpmachine";

                System.Diagnostics.Process process = null;
                try
                {
                    process = System.Diagnostics.Process.Start(processStartInfo);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    throw new Bam.Core.Exception("'{0}': process filename '{1}'", ex.Message, processStartInfo.FileName);
                }

                if (null == process)
                {
                    throw new Bam.Core.Exception("Unable to execute '{0}'", processStartInfo.FileName);
                }

                gccTarget = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                gccTarget = gccTarget.Trim();
            }

            // get paths and targets
            string pathPrefix    = null;
            string gxxIncludeDir = null;
            string libDir        = null;
            var    includePaths  = new Bam.Core.StringArray();
            {
                var processStartInfo = new System.Diagnostics.ProcessStartInfo();
                processStartInfo.FileName               = toolset.Tool(typeof(C.ICompilerTool)).Executable(baseTarget);
                processStartInfo.ErrorDialog            = true;
                processStartInfo.UseShellExecute        = false;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardError  = true;
                processStartInfo.Arguments              = "-v";

                System.Diagnostics.Process process = null;
                try
                {
                    process = System.Diagnostics.Process.Start(processStartInfo);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    throw new Bam.Core.Exception("'{0}': process filename '{1}'", ex.Message, processStartInfo.FileName);
                }

                if (null == process)
                {
                    throw new Bam.Core.Exception("Unable to execute '{0}'", processStartInfo.FileName);
                }

                var details = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                var splitDetails = details.Split(new string[] { System.Environment.NewLine }, System.StringSplitOptions.None);

                foreach (var detail in splitDetails)
                {
                    const string configuredWith = "Configured with: ";
                    if (detail.StartsWith(configuredWith))
                    {
                        var configuredOptions     = detail.Substring(configuredWith.Length);
                        var splitConfigureOptions = configuredOptions.Split(' ');

                        const string pathPrefixKey    = "--prefix=";
                        const string gxxIncludeDirKey = "--with-gxx-include-dir=";
                        const string targetKey        = "--target=";
                        const string libexecKey       = "--libexecdir=";
                        const string slibDirKey       = "--with-slibdir=";
                        foreach (var option in splitConfigureOptions)
                        {
                            if (option.StartsWith(pathPrefixKey))
                            {
                                pathPrefix = option.Substring(pathPrefixKey.Length).Trim();;
                            }
                            else if (option.StartsWith(gxxIncludeDirKey))
                            {
                                gxxIncludeDir = option.Substring(gxxIncludeDirKey.Length).Trim();
                            }
                            else if (option.StartsWith(targetKey))
                            {
                                gccTarget = option.Substring(targetKey.Length).Trim();
                            }
                            else if (option.StartsWith(libexecKey))
                            {
                                if (null != libDir)
                                {
                                    throw new Bam.Core.Exception("lib dir already defined");
                                }
                                libDir = option.Substring(libexecKey.Length).Trim();
                            }
                            else if (option.StartsWith(slibDirKey))
                            {
                                if (null != libDir)
                                {
                                    throw new Bam.Core.Exception("lib dir already defined");
                                }
                                libDir = option.Substring(slibDirKey.Length).Trim();
                            }
                        }

                        break;
                    }
                }

                if (null == gccTarget)
                {
                    foreach (var detail in splitDetails)
                    {
                        var targetKey = "Target: ";
                        if (detail.StartsWith(targetKey))
                        {
                            gccTarget = detail.Substring(targetKey.Length).Trim();
                        }
                    }
                }

                if ((null != gxxIncludeDir) && !gxxIncludeDir.StartsWith(pathPrefix))
                {
                    // remove any prefix directory separator so that Combine works
                    gxxIncludeDir = gxxIncludeDir.TrimStart(System.IO.Path.DirectorySeparatorChar);
                    gxxIncludeDir = System.IO.Path.Combine(pathPrefix, gxxIncludeDir);
                }

                // C include paths (http://gcc.gnu.org/onlinedocs/cpp/Search-Path.html)
                includePaths.Add("/usr/local/include");
                includePaths.Add("/usr/include");

                // TODO: this looks like the targetIncludeFolder, and has been necessary
                {
                    // this is for some Linux distributions
                    var path = System.String.Format("/usr/include/{0}", gccTarget);
                    if (System.IO.Directory.Exists(path))
                    {
                        includePaths.Add(path);
                    }
                }
            }

            var gccDetails = new GccDetailData(gccVersion, includePaths, gxxIncludeDir, gccTarget, libDir);

            gccDetailsForTarget[baseTarget] = gccDetails;

            Bam.Core.Log.DebugMessage("Gcc version for target '{0}' is '{1}'", baseTarget.ToString(), gccDetails.Version);
            Bam.Core.Log.DebugMessage("Gcc machine type for target '{0}' is '{1}'", baseTarget.ToString(), gccDetails.Target);
            Bam.Core.Log.DebugMessage("Gxx include path for target '{0}' is '{1}'", baseTarget.ToString(), gccDetails.GxxIncludePath);

            return(gccDetails);
        }
 CommandLineProcessor.IConvertToCommandLine.Convert(
     Bam.Core.StringArray commandLine)
 {
     CommandLineProcessor.Conversion.Convert(typeof(GccCommon.CommandLineImplementation), this, commandLine);
 }
        Convert(
            this C.ICommonCompilerSettings settings,
            Bam.Core.StringArray commandLine)
        {
            var module = (settings as Bam.Core.Settings).Module;

            if (settings.Bits.HasValue)
            {
                switch (settings.Bits.Value)
                {
                case C.EBit.ThirtyTwo:
                    commandLine.Add("-m32");
                    break;

                case C.EBit.SixtyFour:
                    commandLine.Add("-m64");
                    break;

                default:
                    throw new Bam.Core.Exception("Unknown machine bit depth, {0}", settings.Bits.Value.ToString());
                }
            }
            if (settings.DebugSymbols.HasValue)
            {
                if (settings.DebugSymbols.Value)
                {
                    commandLine.Add("-g");
                }
            }
            foreach (var warning in settings.DisableWarnings)
            {
                commandLine.Add(warning);
            }
            foreach (var path in settings.IncludePaths)
            {
                commandLine.Add(System.String.Format("-I{0}", path.ParseAndQuoteIfNecessary()));
            }
            if (settings.OmitFramePointer.HasValue)
            {
                commandLine.Add(settings.OmitFramePointer.Value ? "-fomit-frame-pointer" : "-fno-omit-frame-pointer");
            }
            if (settings.Optimization.HasValue)
            {
                switch (settings.Optimization.Value)
                {
                case C.EOptimization.Off:
                    commandLine.Add("-O0");
                    break;

                case C.EOptimization.Size:
                    commandLine.Add("-Os");
                    break;

                case C.EOptimization.Speed:
                    commandLine.Add("-O1");
                    break;

                case C.EOptimization.Full:
                    commandLine.Add("-O3");
                    break;

                default:
                    throw new Bam.Core.Exception("Unknown optimization level, {0}", settings.Optimization.Value.ToString());
                }
            }
            foreach (var define in settings.PreprocessorDefines)
            {
                if (System.String.IsNullOrEmpty(define.Value))
                {
                    commandLine.Add(System.String.Format("-D{0}", define.Key));
                }
                else
                {
                    var value = define.Value;
                    if (value.Contains("\""))
                    {
                        value = value.Replace("\"", "\\\"");
                    }
                    commandLine.Add(System.String.Format("-D{0}={1}", define.Key, value));
                }
            }
            foreach (var undefine in settings.PreprocessorUndefines)
            {
                commandLine.Add(System.String.Format("-U{0}", undefine));
            }
            foreach (var path in settings.SystemIncludePaths)
            {
                commandLine.Add(System.String.Format("-I{0}", path.ParseAndQuoteIfNecessary()));
            }
            if (settings.TargetLanguage.HasValue)
            {
                switch (settings.TargetLanguage.Value)
                {
                case C.ETargetLanguage.C:
                    commandLine.Add("-x c");
                    break;

                case C.ETargetLanguage.Cxx:
                    commandLine.Add("-x c++");
                    break;

                default:
                    throw new Bam.Core.Exception("Unsupported target language, {0}", settings.TargetLanguage.Value.ToString());
                }
            }
            if (settings.WarningsAsErrors.HasValue)
            {
                if (settings.WarningsAsErrors.Value)
                {
                    commandLine.Add("-Werror");
                }
            }
            if (settings.OutputType.HasValue)
            {
                switch (settings.OutputType.Value)
                {
                case C.ECompilerOutput.CompileOnly:
                    commandLine.Add(System.String.Format("-c -o {0}", module.GeneratedPaths[C.ObjectFile.Key].ToString()));
                    break;

                case C.ECompilerOutput.Preprocess:
                    commandLine.Add(System.String.Format("-E -o {0}", module.GeneratedPaths[C.ObjectFile.Key].ToString()));
                    break;
                }
            }
        }
Exemple #51
0
        ICollatedObjectPolicy.Collate(
            CollatedObject sender,
            Bam.Core.ExecutionContext context)
        {
            var sourcePath = sender.SourcePath;

            if (null == sender.Reference)
            {
                if ((null != sender.SourceModule.MetaData) || (sender.SourceModule is CollatedObject))
                {
                    // the main file is not copied anywhere, as we copy required files around it where VS wrote the main file
                    // this is managed by the Collation class, querying the build mode for where publishing is relative to
                    // ignore any subdirectory on this module

                    // could also be a DebugSymbols or Stripped copy, in which case, ignore it
                    return;
                }
                else
                {
                    // the main reference file was a prebuilt - so create a new project to handle copying files

                    var solution = Bam.Core.Graph.Instance.MetaData as VSSolutionBuilder.VSSolution;
                    var project  = solution.EnsureProjectExists(sender.SourceModule);
                    var config   = project.GetConfiguration(sender.SourceModule);

                    config.SetType(VSSolutionBuilder.VSProjectConfiguration.EType.Utility);
                    config.SetOutputPath(sender.Macros["CopyDir"]);
                    config.EnableIntermediatePath();
                }
            }

            var commandLine = new Bam.Core.StringArray();

            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            if (sender.SourceModule != null && sender.SourceModule.MetaData != null && VSSolutionBuilder.VSProject.IsBuildable(sender.SourceModule))
            {
                var destinationPath = sender.Macros["CopyDir"].Parse();

                var project = sender.SourceModule.MetaData as VSSolutionBuilder.VSProject;
                var config  = project.GetConfiguration(sender.SourceModule);

                var commands = new Bam.Core.StringArray();
                commands.Add(System.String.Format("IF NOT EXIST {0} MKDIR {0}", destinationPath));
                if (config.Type != VSSolutionBuilder.VSProjectConfiguration.EType.Utility)
                {
                    commands.Add(System.String.Format(@"{0} {1} $(OutputPath)$(TargetFileName) {2} {3}",
                                                      CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                      commandLine.ToString(' '),
                                                      destinationPath,
                                                      CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                    config.AddPostBuildCommands(commands);
                }
                else
                {
                    commands.Add(System.String.Format(@"{0} {1} {2} $(OutDir).\ {3}",
                                                      CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                      commandLine.ToString(' '),
                                                      sourcePath.ParseAndQuoteIfNecessary(),
                                                      CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                    config.AddPreBuildCommands(commands);
                }
            }
            else
            {
                var commands = new Bam.Core.StringArray();
                if (sender is CollatedDirectory)
                {
                    // Windows XCOPY requires the directory name to be added to the destination, while Posix cp does not
                    commands.Add(System.String.Format(@"{0} {1} {2} $(OutDir){3}\ {4}",
                                                      CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                      commandLine.ToString(' '),
                                                      sourcePath.ParseAndQuoteIfNecessary(),
                                                      sender.CreateTokenizedString("$(0)/@ifnotempty($(CopiedFilename),$(CopiedFilename),@filename($(1)))", sender.SubDirectory, sourcePath).Parse(),
                                                      CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                }
                else
                {
                    commands.Add(System.String.Format(@"{0} {1} {2} $(OutDir){3}\ {4}",
                                                      CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                      commandLine.ToString(' '),
                                                      sourcePath.ParseAndQuoteIfNecessary(),
                                                      sender.SubDirectory,
                                                      CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                }

                var project = sender.Reference.SourceModule.MetaData as VSSolutionBuilder.VSProject;
                var config  = project.GetConfiguration(sender.Reference.SourceModule);
                if (config.Type != VSSolutionBuilder.VSProjectConfiguration.EType.Utility)
                {
                    config.AddPostBuildCommands(commands);
                }
                else
                {
                    config.AddPreBuildCommands(commands);
                }
            }
        }
Exemple #52
0
 AddPostBuildCommands(
     Bam.Core.StringArray commands)
 {
     this.PostBuildCommands.AddRange(commands);
 }
        ICollatedObjectPolicy.Collate(
            CollatedObject sender,
            Bam.Core.ExecutionContext context)
        {
            var meta = new MakeFileBuilder.MakeFileMeta(sender);
            var rule = meta.AddRule();

            var sourcePath     = sender.SourcePath;
            var sourceFilename = System.IO.Path.GetFileName(sourcePath.Parse());

            var topLevel   = sender.GetEncapsulatingReferencedModule().GetType().Name;
            var senderType = sender.GetType().Name;
            var sourceType = (null != sender.SourceModule) ? sender.SourceModule.GetType().FullName : "publishroot";
            var basename   = sourceType + "_" + topLevel + "_" + senderType + "_" + sender.BuildEnvironment.Configuration.ToString() + "_";

            var isSymLink    = sender is CollatedSymbolicLink;
            var isDir        = sender is CollatedDirectory;
            var isRenamedDir = sender.Tool is CopyFilePosix & sender.Macros["CopiedFilename"].IsAliased;

            if (isSymLink)
            {
                rule.AddTarget(sender.GeneratedPaths[CollatedObject.Key], variableName: basename + sourceFilename, isPhony: true);
            }
            else
            {
                if (isDir)
                {
                    if (isRenamedDir)
                    {
                        var rename = sender.Macros["CopiedFilename"].Parse();
                        rule.AddTarget(Bam.Core.TokenizedString.CreateVerbatim(basename + rename), isPhony: true);
                    }
                    else
                    {
                        var targetName = sender.CreateTokenizedString("$(0)/@filename($(1))", sender.Macros["CopyDir"], sourcePath);
                        rule.AddTarget(targetName, variableName: basename + sourceFilename);
                    }
                }
                else
                {
                    rule.AddTarget(sender.GeneratedPaths[CollatedObject.Key], variableName: basename + sourceFilename);
                }
            }

            meta.CommonMetaData.Directories.AddUnique(sender.Macros["CopyDir"].Parse());

            var commandLine = new Bam.Core.StringArray();

            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            if (isSymLink)
            {
                rule.AddShellCommand(System.String.Format(@"{0} {1} {2} $@ {3}",
                                                          CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                          commandLine.ToString(' '),
                                                          sender.Macros["LinkTarget"].Parse(),
                                                          CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
            }
            else
            {
                if (isDir)
                {
                    if (isRenamedDir)
                    {
                        rule.AddShellCommand(System.String.Format(@"{0} {1} $</* {2} {3}",
                                                                  CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                                  commandLine.ToString(' '),
                                                                  sender.Macros["CopyDir"].Parse(),
                                                                  CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                    }
                    else
                    {
                        rule.AddShellCommand(System.String.Format(@"{0} {1} $< $(dir $@) {2}",
                                                                  CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                                  commandLine.ToString(' '),
                                                                  CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                    }
                }
                else
                {
                    rule.AddShellCommand(System.String.Format(@"{0} {1} $< $(dir $@) {2}",
                                                              CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                              commandLine.ToString(' '),
                                                              CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)),
                                         ignoreErrors: !(sender as CollatedFile).FailWhenSourceDoesNotExist);
                }
                rule.AddPrerequisite(sourcePath);
            }
        }
        Convert(
            this GccCommon.ICommonCompilerSettings settings,
            Bam.Core.StringArray commandLine)
        {
            if (settings.PositionIndependentCode.HasValue)
            {
                if (settings.PositionIndependentCode.Value)
                {
                    commandLine.Add("-fPIC");
                }
            }
            if (settings.AllWarnings.HasValue)
            {
                if (settings.AllWarnings.Value)
                {
                    commandLine.Add("-Wall");
                }
            }
            if (settings.ExtraWarnings.HasValue)
            {
                if (settings.ExtraWarnings.Value)
                {
                    commandLine.Add("-Wextra");
                }
            }
            if (settings.Pedantic.HasValue)
            {
                if (settings.Pedantic.Value)
                {
                    commandLine.Add("-pedantic");
                }
            }
            if (settings.Visibility.HasValue)
            {
                switch (settings.Visibility.Value)
                {
                case EVisibility.Default:
                    commandLine.Add("-fvisibility=default");
                    break;

                case EVisibility.Hidden:
                    commandLine.Add("-fvisibility=hidden");
                    break;

                case EVisibility.Internal:
                    commandLine.Add("-fvisibility=internal");
                    break;

                case EVisibility.Protected:
                    commandLine.Add("-fvisibility=protected");
                    break;

                default:
                    throw new Bam.Core.Exception("Unrecognized visibility, {0}", settings.Visibility.Value.ToString());
                }
            }
            if (settings.StrictAliasing.HasValue)
            {
                if (settings.StrictAliasing.Value)
                {
                    commandLine.Add("-fstrict-aliasing");
                }
            }
        }
        Convert(
            this C.ICommonCompilerSettings settings,
            Bam.Core.StringArray commandLine)
        {
            if (settings.Bits.HasValue)
            {
                switch (settings.Bits.Value)
                {
                case C.EBit.SixtyFour:
                    commandLine.Add("-arch x86_64");
                    break;

                case C.EBit.ThirtyTwo:
                    commandLine.Add("-arch i386");
                    break;

                default:
                    throw new Bam.Core.Exception("Unknown bit depth, {0}", settings.Bits.Value);
                }
            }
            if (settings.DebugSymbols.HasValue)
            {
                if (settings.DebugSymbols.Value)
                {
                    commandLine.Add("-g");
                }
            }
            foreach (var warning in settings.DisableWarnings)
            {
                commandLine.Add(System.String.Format("-Wno-{0}", warning));
            }
            foreach (var path in settings.IncludePaths.ToEnumerableWithoutDuplicates())
            {
                var quoted_path = path.ToStringQuoteIfNecessary();
                if (Bam.Core.Graph.Instance.Mode == "Xcode")
                {
                    quoted_path = quoted_path.Replace("\"", "\\\"");
                }
                commandLine.Add(System.String.Format("-I{0}", quoted_path));
            }
            if (settings.Optimization.HasValue)
            {
                switch (settings.Optimization.Value)
                {
                case C.EOptimization.Off:
                    commandLine.Add("-O0");
                    break;

                case C.EOptimization.Size:
                    commandLine.Add("-Os");
                    break;

                case C.EOptimization.Speed:
                    commandLine.Add("-O2");
                    break;

                case C.EOptimization.Custom:
                    // do nothing - defer to the compiler specific optimization settings
                    break;

                default:
                    throw new Bam.Core.Exception("Unsupported optimization, {0}", settings.Optimization.Value);
                }
            }
            if (settings.OmitFramePointer.HasValue)
            {
                commandLine.Add(settings.OmitFramePointer.Value ? "-fomit-frame-pointer" : "-fno-omit-frame-pointer");
            }
            foreach (var define in settings.PreprocessorDefines)
            {
                if (null == define.Value)
                {
                    commandLine.Add(System.String.Format("-D{0}", define.Key));
                }
                else
                {
                    var defineValue = define.Value.ToString();
                    if (defineValue.Contains("\""))
                    {
                        if (Bam.Core.Graph.Instance.Mode == "Xcode")
                        {
                            // note the number of back slashes here
                            // required to get \\\" for each " in the original value
                            defineValue = defineValue.Replace("\"", "\\\\\\\"");
                        }
                        else
                        {
                            defineValue = defineValue.Replace("\"", "\\\"");
                        }
                    }
                    defineValue = Bam.Core.IOWrapper.EncloseSpaceContainingPathWithDoubleQuotes(defineValue);
                    commandLine.Add(System.String.Format("-D{0}={1}", define.Key, defineValue));
                }
            }
            foreach (var undefine in settings.PreprocessorUndefines)
            {
                commandLine.Add(System.String.Format("-U{0}", undefine));
            }
            foreach (var path in settings.SystemIncludePaths.ToEnumerableWithoutDuplicates())
            {
                var quoted_path = path.ToStringQuoteIfNecessary();
                if (Bam.Core.Graph.Instance.Mode == "Xcode")
                {
                    quoted_path = quoted_path.Replace("\"", "\\\"");
                }
                commandLine.Add(System.String.Format("-I{0}", quoted_path));
            }
            if (settings.TargetLanguage.HasValue)
            {
                switch (settings.TargetLanguage.Value)
                {
                case C.ETargetLanguage.C:
                    commandLine.Add("-x c");
                    break;

                case C.ETargetLanguage.Cxx:
                    commandLine.Add("-x c++");
                    break;

                case C.ETargetLanguage.ObjectiveC:
                    commandLine.Add("-x objective-c");
                    break;

                case C.ETargetLanguage.ObjectiveCxx:
                    commandLine.Add("-x objective-c++");
                    break;

                default:
                    throw new Bam.Core.Exception("Unsupported target language, {0}", settings.TargetLanguage.Value);
                }
            }
            if (settings.WarningsAsErrors.HasValue)
            {
                if (settings.WarningsAsErrors.Value)
                {
                    commandLine.Add("-Werror");
                }
                else
                {
                    commandLine.Add("-Wno-error");
                }
            }
            if (settings.OutputType.HasValue)
            {
                var module = (settings as Bam.Core.Settings).Module;
                switch (settings.OutputType.Value)
                {
                case C.ECompilerOutput.CompileOnly:
                    commandLine.Add(System.String.Format("-c -o {0}", module.GeneratedPaths[C.ObjectFile.Key].ToStringQuoteIfNecessary()));
                    break;

                case C.ECompilerOutput.Preprocess:
                    commandLine.Add(System.String.Format("-E -o {0}", module.GeneratedPaths[C.ObjectFile.Key].ToStringQuoteIfNecessary()));
                    break;

                default:
                    throw new Bam.Core.Exception("Unsupported output type, {0}", settings.OutputType.Value.ToString());
                }
            }
            foreach (var header in settings.NamedHeaders)
            {
                commandLine.Add(System.String.Format("-include {0}", header));
            }
        }
        Convert(
            this GccCommon.ICommonCompilerSettings settings,
            Bam.Core.StringArray commandLine)
        {
            if (settings.PositionIndependentCode.HasValue)
            {
                if (settings.PositionIndependentCode.Value)
                {
                    commandLine.Add("-fPIC");
                }
            }
            if (settings.AllWarnings.HasValue)
            {
                if (settings.AllWarnings.Value)
                {
                    commandLine.Add("-Wall");
                }
                else
                {
                    commandLine.Add("-Wno-all");
                }
            }
            if (settings.ExtraWarnings.HasValue)
            {
                if (settings.ExtraWarnings.Value)
                {
                    commandLine.Add("-Wextra");
                }
                else
                {
                    commandLine.Add("-Wno-extra");
                }
            }
            if (settings.Pedantic.HasValue)
            {
                if (settings.Pedantic.Value)
                {
                    commandLine.Add("-Wpedantic");
                }
                else
                {
                    commandLine.Add("-Wno-pedantic");
                }
            }
            if (settings.Visibility.HasValue)
            {
                switch (settings.Visibility.Value)
                {
                case EVisibility.Default:
                    commandLine.Add("-fvisibility=default");
                    break;

                case EVisibility.Hidden:
                    commandLine.Add("-fvisibility=hidden");
                    break;

                case EVisibility.Internal:
                    commandLine.Add("-fvisibility=internal");
                    break;

                case EVisibility.Protected:
                    commandLine.Add("-fvisibility=protected");
                    break;

                default:
                    throw new Bam.Core.Exception("Unrecognized visibility, {0}", settings.Visibility.Value.ToString());
                }
            }
            if (settings.StrictAliasing.HasValue)
            {
                if (settings.StrictAliasing.Value)
                {
                    commandLine.Add("-fstrict-aliasing");
                }
                else
                {
                    commandLine.Add("-fno-strict-aliasing");
                }
            }
            if (settings.Optimization.HasValue)
            {
                var common_optimization = (settings as C.ICommonCompilerSettings).Optimization;
                if (common_optimization.HasValue && common_optimization.Value != C.EOptimization.Custom)
                {
                    throw new Bam.Core.Exception("Compiler specific optimizations can only be set when the common optimization is C.EOptimization.Custom");
                }

                switch (settings.Optimization.Value)
                {
                case EOptimization.O3:
                    commandLine.Add("-O3");
                    break;

                case EOptimization.Ofast:
                    commandLine.Add("-Ofast");
                    break;

                default:
                    throw new Bam.Core.Exception("Unrecognized GCC optimization, {0}", settings.Optimization.Value.ToString());
                }
            }
        }
 IsSDKValid(
     Bam.Core.StringArray availableSDKs,
     string sdk)
 {
     return(availableSDKs.Contains(sdk));
 }
        Execute(
            Bam.Core.ExecutionContext context,
            string executablePath,
            Bam.Core.StringArray commandLineArguments = null,
            string workingDirectory = null,
            Bam.Core.StringArray inheritedEnvironmentVariables = null,
            System.Collections.Generic.Dictionary <string, Bam.Core.TokenizedStringArray> addedEnvironmentVariables = null,
            string useResponseFileOption = null)
        {
            var processStartInfo = new System.Diagnostics.ProcessStartInfo();

            processStartInfo.FileName    = executablePath;
            processStartInfo.ErrorDialog = true;
            if (null != workingDirectory)
            {
                processStartInfo.WorkingDirectory = workingDirectory;
            }

            var cachedEnvVars = new System.Collections.Generic.Dictionary <string, string>();

            // first get the inherited environment variables from the system environment
            if (null != inheritedEnvironmentVariables)
            {
                int envVarCount;
                if (inheritedEnvironmentVariables.Count == 1 &&
                    inheritedEnvironmentVariables[0] == "*")
                {
                    foreach (System.Collections.DictionaryEntry envVar in processStartInfo.EnvironmentVariables)
                    {
                        cachedEnvVars.Add(envVar.Key as string, envVar.Value as string);
                    }
                }
                else if (inheritedEnvironmentVariables.Count == 1 &&
                         System.Int32.TryParse(inheritedEnvironmentVariables[0], out envVarCount) &&
                         envVarCount < 0)
                {
                    envVarCount += processStartInfo.EnvironmentVariables.Count;
                    foreach (var envVar in processStartInfo.EnvironmentVariables.Cast <System.Collections.DictionaryEntry>().OrderBy(item => item.Key))
                    {
                        cachedEnvVars.Add(envVar.Key as string, envVar.Value as string);
                        --envVarCount;
                        if (0 == envVarCount)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    foreach (var envVar in inheritedEnvironmentVariables)
                    {
                        if (!processStartInfo.EnvironmentVariables.ContainsKey(envVar))
                        {
                            Bam.Core.Log.Info("Environment variable '{0}' does not exist", envVar);
                            continue;
                        }
                        cachedEnvVars.Add(envVar, processStartInfo.EnvironmentVariables[envVar]);
                    }
                }
            }
            processStartInfo.EnvironmentVariables.Clear();
            if (null != inheritedEnvironmentVariables)
            {
                foreach (var envVar in cachedEnvVars)
                {
                    processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
                }
            }
            if (null != addedEnvironmentVariables)
            {
                foreach (var envVar in addedEnvironmentVariables)
                {
                    processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value.ToString(System.IO.Path.PathSeparator);
                }
            }

            processStartInfo.UseShellExecute        = false; // to redirect IO streams
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError  = true;
            processStartInfo.RedirectStandardInput  = true;

            var arguments = commandLineArguments != null?commandLineArguments.ToString(' ') : string.Empty;

            string responseFilePath = null;

            if (Bam.Core.OSUtilities.IsWindowsHosting)
            {
                //TODO: should this include the length of the executable path too?
                if (arguments.Length >= 32767)
                {
                    if (null == useResponseFileOption)
                    {
                        throw new Bam.Core.Exception("Command line is {0} characters long, but response files are not supported by the tool {1}", arguments.Length, executablePath);
                    }

                    responseFilePath = Bam.Core.IOWrapper.CreateTemporaryFile();
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(responseFilePath))
                    {
                        Bam.Core.Log.DebugMessage("Written response file {0} containing:\n{1}", responseFilePath, arguments);
                        // escape any back slashes
                        writer.WriteLine(arguments.Replace(@"\", @"\\"));
                    }

                    arguments = System.String.Format("{0}{1}", useResponseFileOption, responseFilePath);
                }
            }
            processStartInfo.Arguments = arguments;

            Bam.Core.Log.Detail("{0} {1}", processStartInfo.FileName, processStartInfo.Arguments);

            // useful debugging of the command line processor
            Bam.Core.Log.DebugMessage("Working directory: '{0}'", processStartInfo.WorkingDirectory);
            if (processStartInfo.EnvironmentVariables.Count > 0)
            {
                Bam.Core.Log.DebugMessage("Environment variables:");
                foreach (var envVar in processStartInfo.EnvironmentVariables.Cast <System.Collections.DictionaryEntry>().OrderBy(item => item.Key))
                {
                    Bam.Core.Log.DebugMessage("\t{0} = {1}", envVar.Key, envVar.Value);
                }
            }

            System.Diagnostics.Process process = null;
            int exitCode = -1;

            try
            {
                process                     = new System.Diagnostics.Process();
                process.StartInfo           = processStartInfo;
                process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(context.OutputDataReceived);
                process.ErrorDataReceived  += new System.Diagnostics.DataReceivedEventHandler(context.ErrorDataReceived);
                process.Start();
                process.StandardInput.Close();
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                throw new Bam.Core.Exception("'{0}': process filename '{1}'", ex.Message, processStartInfo.FileName);
            }

            if (null != process)
            {
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                // TODO: need to poll for an external cancel op?
                // poll for the process to exit, as some processes seem to get stuck (hdiutil attach, for example)
                while (!process.HasExited)
                {
                    process.WaitForExit(2000);
                }
                // this additional WaitForExit appears to be needed in order to finish reading the output and error streams asynchronously
                // without it, output is missing from a Native build when executed in many threads
                process.WaitForExit();

                exitCode = process.ExitCode;
                //Bam.Core.Log.DebugMessage("Tool exit code: {0}", exitCode);
                process.Close();
            }

            // delete once the process has finished, or never started
            if (null != responseFilePath)
            {
                System.IO.File.Delete(responseFilePath);
            }

            if (exitCode != 0)
            {
                var message = new System.Text.StringBuilder();
                message.AppendFormat("Command failed: {0} {1}", processStartInfo.FileName, processStartInfo.Arguments);
                message.AppendLine();
                if (null != responseFilePath)
                {
                    message.AppendLine("Response file contained:");
                    message.AppendLine(arguments);
                }
                message.AppendFormat("Command exit code: {0}", exitCode);
                message.AppendLine();
                throw new Bam.Core.Exception(message.ToString());
            }
        }
Exemple #59
0
        ILinkingPolicy.Link(
            ConsoleApplication sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString executablePath,
            System.Collections.ObjectModel.ReadOnlyCollection <Bam.Core.Module> objectFiles,
            System.Collections.ObjectModel.ReadOnlyCollection <Bam.Core.Module> headers,
            System.Collections.ObjectModel.ReadOnlyCollection <Bam.Core.Module> libraries)
        {
            if (0 == objectFiles.Count)
            {
                return;
            }

            var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta;
            var target    = workspace.EnsureTargetExists(sender);

            target.EnsureOutputFileReferenceExists(
                sender.CreateTokenizedString("@filename($(0))", executablePath),
                (sender is IDynamicLibrary) ? XcodeBuilder.FileReference.EFileType.DynamicLibrary : XcodeBuilder.FileReference.EFileType.Executable,
                (sender is IDynamicLibrary) ? XcodeBuilder.Target.EProductType.DynamicLibrary : XcodeBuilder.Target.EProductType.Executable);
            var configuration = target.GetConfiguration(sender);

            if (sender is IDynamicLibrary && !((sender is Plugin) || (sender is C.Cxx.Plugin)))
            {
                if (sender.Macros["OutputName"].Equals(sender.Macros["modulename"]))
                {
                    configuration.SetProductName(sender.CreateTokenizedString("${TARGET_NAME}.$(MajorVersion)"));
                }
                else
                {
                    configuration.SetProductName(sender.CreateTokenizedString("$(OutputName).$(MajorVersion)"));
                }
            }
            else
            {
                if (sender.Macros["OutputName"].Equals(sender.Macros["modulename"]))
                {
                    configuration.SetProductName(Bam.Core.TokenizedString.CreateVerbatim("${TARGET_NAME}"));
                }
                else
                {
                    configuration.SetProductName(sender.Macros["OutputName"]);
                }
            }

            foreach (var header in headers)
            {
                target.EnsureHeaderFileExists((header as HeaderFile).InputPath);
            }

            var excludedSource  = new XcodeBuilder.MultiConfigurationValue();
            var realObjectFiles = objectFiles.Where(item => !(item is AssembledObjectFile));

            if (realObjectFiles.Any())
            {
                var xcodeConvertParameterTypes = new Bam.Core.TypeArray
                {
                    typeof(Bam.Core.Module),
                    typeof(XcodeBuilder.Configuration)
                };

                var sharedSettings = C.SettingsBase.SharedSettings(
                    realObjectFiles,
                    typeof(ClangCommon.XcodeCompilerImplementation),
                    typeof(XcodeProjectProcessor.IConvertToProject),
                    xcodeConvertParameterTypes);
                (sharedSettings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration);

                foreach (var objFile in realObjectFiles)
                {
                    if (!(objFile as C.ObjectFileBase).PerformCompilation)
                    {
                        var fullPath = (objFile as C.ObjectFileBase).InputPath.Parse();
                        var filename = System.IO.Path.GetFileName(fullPath);
                        excludedSource.Add(filename);
                    }

                    var buildFile     = objFile.MetaData as XcodeBuilder.BuildFile;
                    var deltaSettings = (objFile.Settings as C.SettingsBase).CreateDeltaSettings(sharedSettings, objFile);
                    if (null != deltaSettings)
                    {
                        var commandLine = new Bam.Core.StringArray();
                        (deltaSettings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);
                        if (commandLine.Count > 0)
                        {
                            // Cannot set per-file-per-configuration settings, so blend them together
                            if (null == buildFile.Settings)
                            {
                                buildFile.Settings = commandLine;
                            }
                            else
                            {
                                buildFile.Settings.AddRangeUnique(commandLine);
                            }
                        }
                    }
                    configuration.BuildFiles.Add(buildFile);
                }

                // now deal with other object file types
                var assembledObjectFiles = objectFiles.Where(item => item is AssembledObjectFile);
                foreach (var asmObj in assembledObjectFiles)
                {
                    var buildFile = asmObj.MetaData as XcodeBuilder.BuildFile;
                    configuration.BuildFiles.Add(buildFile);
                }
            }
            else
            {
                (objectFiles[0].Settings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration);
                foreach (var objFile in objectFiles)
                {
                    if (!(objFile as C.ObjectFileBase).PerformCompilation)
                    {
                        var fullPath = (objFile as C.ObjectFileBase).InputPath.Parse();
                        var filename = System.IO.Path.GetFileName(fullPath);
                        excludedSource.Add(filename);
                    }

                    var buildFile = objFile.MetaData as XcodeBuilder.BuildFile;
                    configuration.BuildFiles.Add(buildFile);
                }
            }

            configuration["EXCLUDED_SOURCE_FILE_NAMES"] = excludedSource;

            // add library search paths prior to converting linker settings
            var linker = sender.Settings as C.ICommonLinkerSettings;

            foreach (var library in libraries)
            {
                if (library is C.StaticLibrary)
                {
                    linker.LibraryPaths.Add(library.CreateTokenizedString("@dir($(0))", library.GeneratedPaths[C.StaticLibrary.Key]));
                }
                else if (library is C.IDynamicLibrary)
                {
                    linker.LibraryPaths.Add(library.CreateTokenizedString("@dir($(0))", library.GeneratedPaths[C.DynamicLibrary.Key]));
                }
                else if (library is C.CSDKModule)
                {
                    // SDK modules are collections of libraries, not one in particular
                    // thus do nothing as they are undefined at this point, and may yet be pulled in automatically
                }
                else if (library is C.HeaderLibrary)
                {
                    // no library
                }
                else if (library is OSXFramework)
                {
                    // frameworks are dealt with elsewhere
                }
                else
                {
                    throw new Bam.Core.Exception("Don't know how to handle this module type, {0}", library.ToString());
                }
            }

            // convert link settings to the Xcode project
            (sender.Settings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration);

            foreach (var library in libraries)
            {
                if (library is C.StaticLibrary)
                {
                    target.DependsOn(library.MetaData as XcodeBuilder.Target);
                }
                else if (library is C.IDynamicLibrary)
                {
                    target.DependsOn(library.MetaData as XcodeBuilder.Target);
                }
                else if (library is C.CSDKModule)
                {
                    // do nothing, just an area for external
                }
                else if (library is C.HeaderLibrary)
                {
                    // no library
                }
                else if (library is OSXFramework)
                {
                    // frameworks are dealt with elsewhere
                }
                else
                {
                    throw new Bam.Core.Exception("Don't know how to handle this module type");
                }
            }

            // order only dependents
            foreach (var required in sender.Requirements)
            {
                if (null == required.MetaData)
                {
                    continue;
                }
                if (required is HeaderLibrary)
                {
                    // the target for a HeaderLibrary has no FileReference output, and thus cannot be an order only dependency
                    continue;
                }

                var requiredTarget = required.MetaData as XcodeBuilder.Target;
                if (null != requiredTarget)
                {
                    target.Requires(requiredTarget);
                }
            }
            // any non-C module projects should be order-only dependencies
            foreach (var dependent in sender.Dependents)
            {
                if (null == dependent.MetaData)
                {
                    continue;
                }
                if (dependent is C.CModule)
                {
                    continue;
                }
                var dependentTarget = dependent.MetaData as XcodeBuilder.Target;
                if (null != dependentTarget)
                {
                    target.Requires(dependentTarget);
                }
            }
        }
        ICollatedObjectPolicy.Collate(
            CollatedObject sender,
            Bam.Core.ExecutionContext context)
        {
            var sourcePath = sender.SourcePath;

            if (null == sender.Reference)
            {
                // the main file is not copied anywhere, as we copy required files around it where Xcode wrote the main file
                // this is managed by the Collation class, querying the build mode for where publishing is relative to
                // ignore any subdirectory on this module

                // convert the executable into an app bundle, if EPublishingType.WindowedApplication has been used as the type
                if ((sender.SubDirectory != null) && sender.SubDirectory.Parse().Contains(".app/"))
                {
                    var target = sender.SourceModule.MetaData as XcodeBuilder.Target;
                    target.MakeApplicationBundle();
                }

                return;
            }

            var commandLine = new Bam.Core.StringArray();

            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine);

            var destinationPath = sender.Macros["CopyDir"].Parse();
            var commands        = new Bam.Core.StringArray();

            commands.Add(System.String.Format("[[ ! -d {0} ]] && mkdir -p {0}", destinationPath));

            if (sender.SourceModule != null && sender.SourceModule.MetaData != null)
            {
                if ((null != sender.Reference) &&
                    (sender.SourceModule.PackageDefinition == sender.Reference.PackageDefinition) &&
                    (null == sender.Reference.SubDirectory) &&
                    (sender.SubDirectory.Parse() == "."))
                {
                    // special case that the module output is already in the right directory at build
                    return;
                }

                commands.Add(System.String.Format("{0} {1} $CONFIGURATION_BUILD_DIR/$EXECUTABLE_NAME {2} {3}",
                                                  CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                  commandLine.ToString(' '),
                                                  destinationPath,
                                                  CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));

                var target        = sender.SourceModule.MetaData as XcodeBuilder.Target;
                var configuration = target.GetConfiguration(sender.SourceModule);
                target.AddPostBuildCommands(commands, configuration);
            }
            else
            {
                var isSymlink = (sender is CollatedSymbolicLink);

                var destinationFolder = "$CONFIGURATION_BUILD_DIR";
                if (sender.Reference != null)
                {
                    destinationFolder = "$CONFIGURATION_BUILD_DIR/$EXECUTABLE_FOLDER_PATH";
                }

                if (isSymlink)
                {
                    commands.Add(System.String.Format("{0} {1} {2} {3}/{4} {5}",
                                                      CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                      commandLine.ToString(' '),
                                                      sender.Macros["LinkTarget"].Parse(),
                                                      destinationFolder,
                                                      sender.CreateTokenizedString("$(0)/@filename($(1))", sender.SubDirectory, sender.SourcePath).Parse(),
                                                      CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                }
                else
                {
                    if (sender is CollatedDirectory)
                    {
                        var copySource = sourcePath.Parse();
                        if (sender.Macros["CopiedFilename"].IsAliased)
                        {
                            copySource = System.String.Format("{0}/*", copySource);
                        }

                        commands.Add(System.String.Format("{0} {1} {2} {3}/{4}/ {5}",
                                                          CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                          commandLine.ToString(' '),
                                                          copySource,
                                                          destinationFolder,
                                                          sender.CreateTokenizedString("$(0)/@ifnotempty($(CopiedFilename),$(CopiedFilename),@filename($(1)))", sender.SubDirectory, sourcePath).Parse(),
                                                          CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                    }
                    else
                    {
                        commands.Add(System.String.Format("{0} {1} {2} {3}/{4}/ {5}",
                                                          CommandLineProcessor.Processor.StringifyTool(sender.Tool as Bam.Core.ICommandLineTool),
                                                          commandLine.ToString(' '),
                                                          sourcePath.Parse(),
                                                          destinationFolder,
                                                          sender.SubDirectory.Parse(),
                                                          CommandLineProcessor.Processor.TerminatingArgs(sender.Tool as Bam.Core.ICommandLineTool)));
                    }
                }

                var target        = sender.Reference.SourceModule.MetaData as XcodeBuilder.Target;
                var configuration = target.GetConfiguration(sender.Reference.SourceModule);
                target.AddPostBuildCommands(commands, configuration);
            }
        }