Beispiel #1
0
        /// <summary>
        /// Implements path interpolation
        /// </summary>
        public static EvaluationResult CreateFromAbsolutePathString(ImmutableContextBase context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var absolutePath = Args.AsString(args, 0);

            var result = AbsolutePath.TryCreate(context.PathTable, absolutePath, out var resultPath, out var characterWithError);

            if (result == AbsolutePath.ParseResult.Success)
            {
                return(EvaluationResult.Create(resultPath));
            }

            string message = string.Format(CultureInfo.CurrentCulture, $"Invalid Absolute path at character: {characterWithError}. ");

            switch (result)
            {
            case AbsolutePath.ParseResult.DevicePathsNotSupported:
                message += "Device Paths are not supported.";
                break;

            case AbsolutePath.ParseResult.FailureDueToInvalidCharacter:
                message += "Character is not a valid path character.";
                break;

            case AbsolutePath.ParseResult.UnknownPathStyle:
                message += "This is not an absolute path.";
                break;

            default:
                throw Contract.AssertFailure("Unexpected path tryparse result type");
            }

            throw new InvalidPathOperationException(message, new ErrorContext(pos: 1));
        }
Beispiel #2
0
        private static EvaluationResult GetStringValue(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var name   = Args.AsString(args, 0);
            var result = GetRawValue(context, name);

            return(result != null?EvaluationResult.Create(result) : EvaluationResult.Undefined);
        }
Beispiel #3
0
        private EvaluationResult RemoveBuildParameter(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var name = Args.AsString(args, 0);

            m_engineAbstraction.RemoveBuildParameter(name);

            return(EvaluationResult.Undefined);
        }
Beispiel #4
0
        private static EvaluationResult Fail(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var message = Args.AsString(args, 0);

            Assert.True(false, message);

            return(EvaluationResult.Undefined);
        }
Beispiel #5
0
        private static EvaluationResult Sha256(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            // AsStringOptional will handle type checks and null check
            string content = Args.AsString(args, 0);

            // getting evaluation result
            return(EvaluationResult.Create(ComputeSha256(content)));
        }
        private static EvaluationResult WriteFileHelper(Context context, ModuleLiteral env, EvaluationStackFrame args, WriteFileMode mode)
        {
            var path        = Args.AsPath(args, 0, false);
            var tags        = Args.AsStringArrayOptional(args, 2);
            var description = Args.AsStringOptional(args, 3);

            PipData pipData;

            switch (mode)
            {
            case WriteFileMode.WriteFile:
                var fileContent = Args.AsIs(args, 1);
                // WriteFile has a separator argument with default newline
                var separator = Args.AsStringOptional(args, 3) ?? Environment.NewLine;
                description = Args.AsStringOptional(args, 4);

                pipData = CreatePipDataForWriteFile(context, fileContent, separator);
                break;

            case WriteFileMode.WriteData:
                var data = Args.AsIs(args, 1);
                pipData = DataProcessor.ProcessData(context, context.FrontEndContext.PipDataBuilderPool, EvaluationResult.Create(data), new ConversionContext(pos: 1));
                break;

            case WriteFileMode.WriteAllLines:
                var lines   = Args.AsArrayLiteral(args, 1);
                var entry   = context.TopStack;
                var newData = ObjectLiteral.Create(
                    new List <Binding>
                {
                    new Binding(context.Names.DataSeparator, Environment.NewLine, entry.InvocationLocation),
                    new Binding(context.Names.DataContents, lines, entry.InvocationLocation),
                },
                    lines.Location,
                    entry.Path);

                pipData = DataProcessor.ProcessData(context, context.FrontEndContext.PipDataBuilderPool, EvaluationResult.Create(newData), new ConversionContext(pos: 1));
                break;

            case WriteFileMode.WriteAllText:
                var text = Args.AsString(args, 1);
                pipData = DataProcessor.ProcessData(context, context.FrontEndContext.PipDataBuilderPool, EvaluationResult.Create(text), new ConversionContext(pos: 1));
                break;

            default:
                throw Contract.AssertFailure("Unknown WriteFileMode.");
            }

            FileArtifact result;

            if (!context.GetPipConstructionHelper().TryWriteFile(path, pipData, WriteFileEncoding.Utf8, tags, description, out result))
            {
                // Error has been logged
                return(EvaluationResult.Error);
            }

            return(new EvaluationResult(result));
        }
Beispiel #7
0
        private static EvaluationResult ExpandEnvironmentVariablesInString(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var unexpandedString = Args.AsString(args, 0);

            if (StringVariableExpander.TryExpandVariablesInString(unexpandedString, context.FrontEndHost.Engine, out string expandedString))
            {
                return(EvaluationResult.Create(expandedString));
            }

            // No expansion occurred
            return(EvaluationResult.Create(unexpandedString));
        }
Beispiel #8
0
        private static EvaluationResult GetBooleanValue(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var    name     = Args.AsString(args, 0);
            string strValue = GetRawValue(context, name);

            if (string.IsNullOrWhiteSpace(strValue) || !bool.TryParse(strValue, out bool value))
            {
                return(ThrowInvalidFormatException <EvaluationResult>(name, strValue, pos: 1));
            }

            return(EvaluationResult.Create(value));
        }
Beispiel #9
0
        private static AbsolutePath GetPathValue(Context context, EvaluationStackFrame args)
        {
            var    name     = Args.AsString(args, 0);
            string strValue = GetRawValue(context, name);

            if (string.IsNullOrWhiteSpace(strValue))
            {
                return(AbsolutePath.Invalid);
            }

            return(ParsePath(context, name, strValue, 1));
        }
Beispiel #10
0
        private static EvaluationResult GetNumberValue(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var    name     = Args.AsString(args, 0);
            string strValue = GetRawValue(context, name);

            if (string.IsNullOrWhiteSpace(strValue) || !int.TryParse(strValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value))
            {
                return(ThrowInvalidFormatException <EvaluationResult>(name, strValue, pos: 1));
            }

            return(EvaluationResult.Create(value));
        }
Beispiel #11
0
        private static EvaluationResult Create(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var fragment = Args.AsString(args, 0);

            var stringTable = context.FrontEndContext.StringTable;

            if (!RelativePath.TryCreate(stringTable, fragment, out RelativePath result))
            {
                throw new InvalidRelativePathException(fragment, new ErrorContext(pos: 1));
            }

            return(EvaluationResult.Create(result));
        }
Beispiel #12
0
        private static EvaluationResult Create(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var atom = Args.AsString(args, 0);

            var stringTable = context.FrontEndContext.StringTable;

            if (!PathAtom.TryCreate(stringTable, atom, out PathAtom result))
            {
                throw new InvalidPathAtomException(atom, new ErrorContext(pos: 1));
            }

            return(EvaluationResult.Create(result));
        }
Beispiel #13
0
        private static EvaluationResult ExpandPaths(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var str       = Args.AsString(args, 0);
            var pathTable = context.FrontEndContext.PathTable;

            return(EvaluationResult.Create(s_expandPathsRegex.Replace(
                                               str,
                                               m =>
            {
                var relPath = RelativePath.Create(context.FrontEndContext.StringTable, m.Groups[1].Value);
                var absPath = context.LastActiveUsedPath.GetParent(pathTable).Combine(pathTable, relPath);
                return absPath.ToString(pathTable);
            })));
        }
Beispiel #14
0
        private static EvaluationResult ParseInt(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var str   = Args.AsString(args, 0);
            var radix = Args.AsIntOptional(args, 1);

            if (radix != null)
            {
                ValidateRadix(radix.Value);
                return(EvaluationResult.Create(Convert.ToInt32(str, radix.Value)));
            }

            if (int.TryParse(str, NumberStyles.Any, s_numberFormatInfo, out int intValue))
            {
                return(EvaluationResult.Create(intValue));
            }

            return(EvaluationResult.Undefined);
        }
Beispiel #15
0
        private static EvaluationResult GetPathValues(Context context, EvaluationStackFrame args, Type type)
        {
            var    name      = Args.AsString(args, 0);
            var    separator = Args.AsString(args, 1);
            string strValue  = GetRawValue(context, name);

            var entry = context.TopStack;

            if (string.IsNullOrWhiteSpace(strValue))
            {
                return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(CollectionUtilities.EmptyArray <EvaluationResult>(), entry.InvocationLocation, entry.Path)));
            }

            var values       = separator.Length == 0 ? new[] { strValue } : strValue.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
            var pathsOrFiles = new List <EvaluationResult>();

            for (int i = 0; i < values.Length; ++i)
            {
                if (!string.IsNullOrWhiteSpace(values[i]))
                {
                    AbsolutePath path = ParsePath(context, name, values[i], 1);

                    EvaluationResult result =
                        type == typeof(AbsolutePath)      ? EvaluationResult.Create(path) :
                        type == typeof(FileArtifact)      ? EvaluationResult.Create(FileArtifact.CreateSourceFile(path)) :
                        type == typeof(DirectoryArtifact) ? EvaluationResult.Create(DirectoryArtifact.CreateWithZeroPartialSealId(path)) :
                        EvaluationResult.Undefined;

                    if (result.IsUndefined)
                    {
                        throw Contract.AssertFailure(I($"Cannot convert paths to typeof({type.Name})"));
                    }

                    pathsOrFiles.Add(result);
                }
            }

            return(EvaluationResult.Create(ArrayLiteral.CreateWithoutCopy(pathsOrFiles.ToArray(), entry.InvocationLocation, entry.Path)));
        }
Beispiel #16
0
        private static EvaluationResult GetFlag(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var    name     = Args.AsString(args, 0);
            string strValue = GetRawValue(context, name);

            if (string.IsNullOrWhiteSpace(strValue))
            {
                return(EvaluationResult.False);
            }

            switch (strValue.ToLowerInvariant())
            {
            case "0":
            case "false":
                return(EvaluationResult.False);

            case "1":
            case "true":
                return(EvaluationResult.True);

            default:
                return(ThrowInvalidFormatException <EvaluationResult>(name, strValue, pos: 1));
            }
        }
Beispiel #17
0
        private static EvaluationResult Join(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var separator      = Args.AsString(args, 0);
            var arrayOfStrings = Args.AsArrayLiteral(args, 1);

            using (var pooledInstance = Pools.StringBuilderPool.GetInstance())
            {
                var builder = pooledInstance.Instance;
                for (var i = 0; i < arrayOfStrings.Length; ++i)
                {
                    var s = Converter.ExpectString(
                        arrayOfStrings[i],
                        new ConversionContext(pos: i, objectCtx: arrayOfStrings));
                    builder.Append(s);

                    if (i < arrayOfStrings.Length - 1)
                    {
                        builder.Append(separator);
                    }
                }

                return(EvaluationResult.Create(builder.ToString()));
            }
        }
Beispiel #18
0
        private EvaluationResult GetKeyForm(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var keyFormDll     = Args.AsFile(args, 0);
            var arch           = Args.AsString(args, 1);
            var name           = Args.AsString(args, 2);
            var version        = Args.AsString(args, 3);
            var publicKeyToken = Args.AsString(args, 4);
            var versionScope   = Args.AsStringOptional(args, 5);
            var culture        = Args.AsStringOptional(args, 6);
            var type           = Args.AsStringOptional(args, 7);

            var handler = m_handlers.GetOrAdd(
                keyFormDll.Path,
                _ =>
            {
                var keyFormDllPath = keyFormDll.Path.ToString(context.PathTable);
                var fileName       = Path.GetFileName(keyFormDllPath);
                if (!string.Equals(KeyFormFileName, fileName, StringComparison.OrdinalIgnoreCase))
                {
                    throw new KeyFormDllWrongFileNameException(keyFormDllPath, KeyFormFileName, new ErrorContext(pos: 1));
                }

                if (!File.Exists(keyFormDllPath))
                {
                    throw new KeyFormDllNotFoundException(keyFormDllPath, new ErrorContext(pos: 1));
                }

                IntPtr moduleHandle = NativeMethods.LoadLibraryW(keyFormDllPath);
                if (moduleHandle == IntPtr.Zero)
                {
                    var lasterror = Marshal.GetLastWin32Error();
                    var ex        = new Win32Exception(lasterror);
                    throw new KeyFormDllLoadException(keyFormDllPath, lasterror, ex.Message, new ErrorContext(pos: 1));
                }

                IntPtr procHandle = NativeMethods.GetProcAddress(moduleHandle, KeyFormFunction);
                if (procHandle == IntPtr.Zero)
                {
                    var lasterror = Marshal.GetLastWin32Error();
                    var ex        = new Win32Exception(lasterror);
                    throw new KeyFormDllLoadException(keyFormDllPath, lasterror, ex.Message, new ErrorContext(pos: 1));
                }

                return(Marshal.GetDelegateForFunctionPointer <GetKeyFormHandler>(procHandle));
            });

            using (var pooledBuilder = m_stringBuilderCache.GetInstance())
            {
                var builder = pooledBuilder.Instance;
                try
                {
                    // Since this is native code hardening our process against threading issues
                    // in the native code by ensuring we only access from single thread.

                    // WIP: experimental. Removing locking for key form.
                    // lock (m_keyFormLock)
                    {
                        handler(arch, name, version, publicKeyToken, versionScope, culture, type, builder, (uint)builder.Capacity);
                    }
                }
                catch (Exception e)
                {
                    // I know it is bad to catch all exceptions, but this is going into native code of which we
                    // don't have control and this code doesn't handle weird input properly.
                    var keyFormDllPath = keyFormDll.Path.ToString(context.PathTable);
                    throw new KeyFormNativeFailureException(keyFormDllPath, e, new ErrorContext(pos: 1));
                }

                return(EvaluationResult.Create(builder.ToString()));
            }
        }
Beispiel #19
0
        /// <summary>
        /// Implements path interpolation
        /// </summary>
        public static EvaluationResult CreateFromAbsolutePathString(ImmutableContextBase context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var absolutePath = Args.AsString(args, 0);

            return(CreateFromAbsolutePathString(context, absolutePath));
        }
Beispiel #20
0
        private EvaluationResult WriteFileHelper(Context context, ModuleLiteral env, EvaluationStackFrame args, WriteFileMode mode)
        {
            AbsolutePath path;

            string[] tags;
            string   description;
            PipData  pipData;

            if (args.Length > 0 && args[0].Value is ObjectLiteral)
            {
                var obj = Args.AsObjectLiteral(args, 0);
                path        = Converter.ExtractPath(obj, m_writeOutputPath, allowUndefined: false);
                tags        = Converter.ExtractStringArray(obj, m_writeTags, allowUndefined: true);
                description = Converter.ExtractString(obj, m_writeDescription, allowUndefined: true);
                switch (mode)
                {
                case WriteFileMode.WriteData:
                    var data = obj[m_writeContents];
                    pipData = ProcessData(context, data, new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllLines:
                    var lines   = Converter.ExtractArrayLiteral(obj, m_writeLines);
                    var entry   = context.TopStack;
                    var newData = ObjectLiteral.Create(
                        new List <Binding>
                    {
                        new Binding(m_dataSeparator, Environment.NewLine, entry.InvocationLocation),
                        new Binding(m_dataContents, lines, entry.InvocationLocation),
                    },
                        lines.Location,
                        entry.Path);

                    pipData = ProcessData(context, EvaluationResult.Create(newData), new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllText:
                    var text = Converter.ExtractString(obj, m_writeText);
                    pipData = ProcessData(context, EvaluationResult.Create(text), new ConversionContext(pos: 1));
                    break;

                default:
                    throw Contract.AssertFailure("Unknown WriteFileMode.");
                }
            }
            else
            {
                path        = Args.AsPath(args, 0, false);
                tags        = Args.AsStringArrayOptional(args, 2);
                description = Args.AsStringOptional(args, 3);

                switch (mode)
                {
                case WriteFileMode.WriteFile:
                    var fileContent = Args.AsIs(args, 1);
                    // WriteFile has a separator argument with default newline
                    var separator = Args.AsStringOptional(args, 3) ?? Environment.NewLine;
                    description = Args.AsStringOptional(args, 4);

                    pipData = CreatePipDataForWriteFile(context, fileContent, separator);
                    break;

                case WriteFileMode.WriteData:
                    var data = Args.AsIs(args, 1);
                    pipData = ProcessData(context, EvaluationResult.Create(data), new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllLines:
                    var lines   = Args.AsArrayLiteral(args, 1);
                    var entry   = context.TopStack;
                    var newData = ObjectLiteral.Create(
                        new List <Binding>
                    {
                        new Binding(m_dataSeparator, Environment.NewLine, entry.InvocationLocation),
                        new Binding(m_dataContents, lines, entry.InvocationLocation),
                    },
                        lines.Location,
                        entry.Path);

                    pipData = ProcessData(context, EvaluationResult.Create(newData), new ConversionContext(pos: 1));
                    break;

                case WriteFileMode.WriteAllText:
                    var text = Args.AsString(args, 1);
                    pipData = ProcessData(context, EvaluationResult.Create(text), new ConversionContext(pos: 1));
                    break;

                default:
                    throw Contract.AssertFailure("Unknown WriteFileMode.");
                }
            }

            FileArtifact result;

            if (!context.GetPipConstructionHelper().TryWriteFile(path, pipData, WriteFileEncoding.Utf8, tags, description, out result))
            {
                // Error has been logged
                return(EvaluationResult.Error);
            }

            return(new EvaluationResult(result));
        }
Beispiel #21
0
        private static EvaluationResult HasVariable(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            var name = Args.AsString(args, 0);

            return(EvaluationResult.Create(GetRawValue(context, name) != null));
        }
Beispiel #22
0
        private static EvaluationResult Fail(Context context, ModuleLiteral env, EvaluationStackFrame args)
        {
            string message = Args.AsString(args, 0);

            throw new ContractFailException(message);
        }