Ejemplo n.º 1
0
        /// <exception cref="ArgumentNullException"><paramref name="destination"/> is null.</exception>
        /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
        public void WriteContentTo(BlobBuilder destination)
        {
            if (destination == null)
            {
                Throw.ArgumentNull(nameof(destination));
            }

            foreach (var chunk in GetChunks())
            {
                destination.WriteBytes(chunk._buffer, 0, chunk.Length);
            }
        }
Ejemplo n.º 2
0
        /// <exception cref="ArgumentNullException"><paramref name="destination"/> is default(<see cref="BlobWriter"/>).</exception>
        /// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
        public void WriteContentTo(ref BlobWriter destination)
        {
            if (destination.IsDefault)
            {
                Throw.ArgumentNull(nameof(destination));
            }

            foreach (var chunk in GetChunks())
            {
                destination.WriteBytes(chunk._buffer, 0, chunk.Length);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Writes UTF16 (little-endian) encoded string at the current position.
        /// </summary>
        /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
        public void WriteUTF16(string value)
        {
            if (value == null)
            {
                Throw.ArgumentNull(nameof(value));
            }

            fixed(char *ptr = value)
            {
                WriteBytesUnchecked((byte *)ptr, value.Length * sizeof(char));
            }
        }
Ejemplo n.º 4
0
        protected PEBuilder(PEHeaderBuilder header, Func <IEnumerable <Blob>, BlobContentId> deterministicIdProvider)
        {
            if (header == null)
            {
                Throw.ArgumentNull(nameof(header));
            }

            IdProvider      = deterministicIdProvider ?? BlobContentId.GetTimeBasedProvider();
            IsDeterministic = deterministicIdProvider != null;
            Header          = header;
            _lazySections   = new Lazy <ImmutableArray <Section> >(CreateSections);
        }
Ejemplo n.º 5
0
        private void ValidateLabel(LabelHandle label, string parameterName)
        {
            if (label.IsNil)
            {
                Throw.ArgumentNull(parameterName);
            }

            if (label.Id > _labels.Count)
            {
                Throw.LabelDoesntBelongToBuilder(parameterName);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Encodes array shape.
        /// </summary>
        /// <param name="rank">The number of dimensions in the array (shall be 1 or more).</param>
        /// <param name="sizes">
        /// Dimension sizes. The array may be shorter than <paramref name="rank"/> but not longer.
        /// </param>
        /// <param name="lowerBounds">
        /// Dimension lower bounds, or <c>default(<see cref="ImmutableArray{Int32}"/>)</c> to set all <paramref name="rank"/> lower bounds to 0.
        /// The array may be shorter than <paramref name="rank"/> but not longer.
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="rank"/> is outside of range [1, 0xffff],
        /// smaller than <paramref name="sizes"/>.Length, or
        /// smaller than <paramref name="lowerBounds"/>.Length.
        /// </exception>
        /// <exception cref="ArgumentNullException"><paramref name="sizes"/> is null.</exception>
        public void Shape(int rank, ImmutableArray <int> sizes, ImmutableArray <int> lowerBounds)
        {
            // The specification doesn't impose a limit on the max number of array dimensions.
            // The CLR supports <64. More than 0xffff is causing crashes in various tools (ildasm).
            if (unchecked ((uint)(rank - 1)) > ushort.MaxValue - 1)
            {
                Throw.ArgumentOutOfRange(nameof(rank));
            }

            if (sizes.IsDefault)
            {
                Throw.ArgumentNull(nameof(sizes));
            }

            // rank
            Builder.WriteCompressedInteger(rank);

            // sizes
            if (sizes.Length > rank)
            {
                Throw.ArgumentOutOfRange(nameof(rank));
            }

            Builder.WriteCompressedInteger(sizes.Length);
            foreach (int size in sizes)
            {
                Builder.WriteCompressedInteger(size);
            }

            // lower bounds
            if (lowerBounds.IsDefault) // TODO: remove -- update Roslyn
            {
                Builder.WriteCompressedInteger(rank);
                for (int i = 0; i < rank; i++)
                {
                    Builder.WriteCompressedSignedInteger(0);
                }
            }
            else
            {
                if (lowerBounds.Length > rank)
                {
                    Throw.ArgumentOutOfRange(nameof(rank));
                }

                Builder.WriteCompressedInteger(lowerBounds.Length);
                foreach (int lowerBound in lowerBounds)
                {
                    Builder.WriteCompressedSignedInteger(lowerBound);
                }
            }
        }
    public static T MustNotBeNullReference <T>([ValidatedNotNull] this T parameter, [CallerArgumentExpression("parameter")] string?parameterName = null, string?message = null)
    {
        if (default(T) != null)
        {
            return(parameter);
        }

        if (parameter is null)
        {
            Throw.ArgumentNull(parameterName, message);
        }
        return(parameter);
    }
Ejemplo n.º 8
0
        public void Name(string name)
        {
            if (name == null)
            {
                Throw.ArgumentNull(nameof(name));
            }
            if (name.Length == 0)
            {
                Throw.ArgumentEmptyString(nameof(name));
            }

            Builder.WriteSerializedString(name);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates a metadata provider over an image stored in memory.
        /// </summary>
        /// <param name="start">Pointer to the start of the metadata blob.</param>
        /// <param name="size">The size of the metadata blob.</param>
        /// <exception cref="ArgumentNullException"><paramref name="start"/> is <see cref="IntPtr.Zero"/>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is negative.</exception>
        /// <remarks>
        /// The memory is owned by the caller and not released on disposal of the <see cref="MetadataReaderProvider"/>.
        /// The caller is responsible for keeping the memory alive and unmodified throughout the lifetime of the <see cref="MetadataReaderProvider"/>.
        /// The content of the blob is not read during the construction of the <see cref="MetadataReaderProvider"/>
        /// </remarks>
        public static unsafe MetadataReaderProvider FromMetadataImage(byte *start, int size)
        {
            if (start is null)
            {
                Throw.ArgumentNull(nameof(start));
            }

            if (size < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(size));
            }

            return(new MetadataReaderProvider(new ExternalMemoryBlockProvider(start, size)));
        }
Ejemplo n.º 10
0
        internal static MemoryBlock CreateChecked(byte *buffer, int length)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length));
            }

            if (buffer == null && length != 0)
            {
                Throw.ArgumentNull(nameof(buffer));
            }

            return(new MemoryBlock(buffer, length));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Adds an entry.
        /// </summary>
        /// <typeparam name="TData">Type of data passed to <paramref name="dataSerializer"/>.</typeparam>
        /// <param name="type">Entry type.</param>
        /// <param name="version">Entry version.</param>
        /// <param name="stamp">Entry stamp.</param>
        /// <param name="data">Data passed to <paramref name="dataSerializer"/>.</param>
        /// <param name="dataSerializer">Serializes data to a <see cref="BlobBuilder"/>.</param>
        public void AddEntry <TData>(DebugDirectoryEntryType type, uint version, uint stamp, TData data, Action <BlobBuilder, TData> dataSerializer)
        {
            if (dataSerializer == null)
            {
                Throw.ArgumentNull(nameof(dataSerializer));
            }

            int start = _dataBuilder.Count;

            dataSerializer(_dataBuilder, data);
            int dataSize = _dataBuilder.Count - start;

            AddEntry(type, version, stamp, dataSize);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates a <see cref="MetadataStringDecoder"/> for the given encoding.
        /// </summary>
        /// <param name="encoding">The encoding to use.</param>
        /// <remarks>
        /// To cache and reuse existing strings. Create a derived class and override <see cref="GetString(byte*, int)"/>
        /// </remarks>
        public MetadataStringDecoder(Encoding encoding)
        {
            if (encoding is null)
            {
                Throw.ArgumentNull(nameof(encoding));
            }

            // Non-enforcement of (encoding is UTF8Encoding) here is by design.
            //
            // This type is not itself aware of any particular encoding. However, the constructor argument that accepts a
            // MetadataStringDecoder argument is validated however because it must be a UTF8 decoder.

            Encoding = encoding;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Returns the number of rows in the specified table.
        /// </summary>
        /// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception>
        public static int GetTableRowCount(this MetadataReader reader, TableIndex tableIndex)
        {
            if (reader == null)
            {
                Throw.ArgumentNull(nameof(reader));
            }

            if ((int)tableIndex >= MetadataTokens.TableCount)
            {
                Throw.TableIndexOutOfRange();
            }

            return(reader.TableRowCounts[(int)tableIndex]);
        }
Ejemplo n.º 14
0
        /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception>
        public unsafe void WriteBytes(byte* buffer, int byteCount)
        {
            if (buffer == null)
            {
                Throw.ArgumentNull(nameof(buffer));
            }

            if (byteCount < 0)
            {
                Throw.ArgumentOutOfRange(nameof(byteCount));
            }

            WriteBytesUnchecked(buffer, byteCount);
        }
Ejemplo n.º 15
0
        public void Sign(BlobBuilder peImage, Func <IEnumerable <Blob>, byte[]> signatureProvider)
        {
            if (peImage == null)
            {
                Throw.ArgumentNull(nameof(peImage));
            }

            if (signatureProvider == null)
            {
                Throw.ArgumentNull(nameof(signatureProvider));
            }

            Sign(peImage, _lazyStrongNameSignature, signatureProvider);
        }
Ejemplo n.º 16
0
        public void Enum(string enumTypeName)
        {
            if (enumTypeName == null)
            {
                Throw.ArgumentNull(nameof(enumTypeName));
            }
            if (enumTypeName.Length == 0)
            {
                Throw.ArgumentEmptyString(nameof(enumTypeName));
            }

            WriteTypeCode(SerializationTypeCode.Enum);
            Builder.WriteSerializedString(enumTypeName);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Creates a new SignatureDecoder.
        /// </summary>
        /// <param name="provider">The provider used to obtain type symbols as the signature is decoded.</param>
        /// <param name="metadataReader">
        /// The metadata reader from which the signature was obtained. It may be null if the given provider allows it.
        /// </param>
        /// <param name="genericContext">
        /// Additional context needed to resolve generic parameters.
        /// </param>
        public SignatureDecoder(
            ISignatureTypeProvider <TType, TGenericContext> provider,
            MetadataReader metadataReader,
            TGenericContext genericContext)
        {
            if (provider == null)
            {
                Throw.ArgumentNull(nameof(provider));
            }

            _metadataReaderOpt = metadataReader;
            _provider          = provider;
            _genericContext    = genericContext;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Creates a Portable Executable reader over a PE image stored in memory.
        /// </summary>
        /// <param name="peImage">Pointer to the start of the PE image.</param>
        /// <param name="size">The size of the PE image.</param>
        /// <param name="isLoadedImage">True if the PE image has been loaded into memory by the OS loader.</param>
        /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is <see cref="IntPtr.Zero"/>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is negative.</exception>
        /// <remarks>
        /// The memory is owned by the caller and not released on disposal of the <see cref="PEReader"/>.
        /// The caller is responsible for keeping the memory alive and unmodified throughout the lifetime of the <see cref="PEReader"/>.
        /// The content of the image is not read during the construction of the <see cref="PEReader"/>
        /// </remarks>
        public unsafe PEReader(byte *peImage, int size, bool isLoadedImage)
        {
            if (peImage is null)
            {
                Throw.ArgumentNull(nameof(peImage));
            }

            if (size < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(size));
            }

            _peImage      = new ExternalMemoryBlockProvider(peImage, size);
            IsLoadedImage = isLoadedImage;
        }
Ejemplo n.º 19
0
        public void AddEmbeddedPortablePdbEntry(BlobBuilder debugMetadata, ushort portablePdbVersion)
        {
            if (debugMetadata == null)
            {
                Throw.ArgumentNull(nameof(debugMetadata));
            }

            int dataSize = WriteEmbeddedPortablePdbData(_dataBuilder, debugMetadata);

            AddEntry(
                type: DebugDirectoryEntryType.EmbeddedPortablePdb,
                version: PortablePdbVersions.DebugDirectoryEmbeddedVersion(portablePdbVersion),
                stamp: 0,
                dataSize: dataSize);
        }
            internal AsyncPipeStream(PipeReader reader, PipeWriter writer, string name)
            {
                if (reader == null && writer == null)
                {
                    Throw.ArgumentNull("At least one of reader/writer must be provided");
                }
                _reader = reader;
                _writer = writer;

                if (string.IsNullOrWhiteSpace(name))
                {
                    name = GetType().Name;
                }
                Name = name.Trim();
            }
Ejemplo n.º 21
0
        public static T MustNotBeNullReferenceV1 <T>(this T parameter, string parameterName = null, string message = null)
        {
            if (default(T) == null)
            {
                if (parameter != null)
                {
                    return(parameter);
                }

                Throw.ArgumentNull(parameterName, message);
                return(default(T));
            }

            return(parameter);
        }
Ejemplo n.º 22
0
        public static T MustNotBeNullReference <T>(this T parameter, string?parameterName = null, string?message = null)
        {
#pragma warning disable CS8653 // It's ok if T is resolved to a reference type. This method is usually used in generic contexts.
            if (default(T) != null)
#pragma warning restore CS8653
            {
                return(parameter);
            }

            if (parameter == null)
            {
                Throw.ArgumentNull(parameterName, message);
            }
            return(parameter);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates a provider for a stream of the specified size beginning at its current position.
        /// </summary>
        /// <param name="stream">Stream.</param>
        /// <param name="size">Size of the metadata blob in the stream. If not specified the metadata blob is assumed to span to the end of the stream.</param>
        /// <param name="options">
        /// Options specifying how sections of the image are read from the stream.
        ///
        /// Unless <see cref="MetadataStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="MetadataReaderProvider"/>
        /// upon successful argument validation. It will be disposed by the <see cref="MetadataReaderProvider"/> and the caller must not manipulate it.
        ///
        /// Unless <see cref="MetadataStreamOptions.PrefetchMetadata"/> is specified no data
        /// is read from the stream during the construction of the <see cref="MetadataReaderProvider"/>. Furthermore, the stream must not be manipulated
        /// by caller while the <see cref="MetadataReaderProvider"/> is alive and undisposed.
        ///
        /// If <see cref="MetadataStreamOptions.PrefetchMetadata"/>, the <see cref="MetadataReaderProvider"/>
        /// will have read all of the data requested during construction. As such, if <see cref="MetadataStreamOptions.LeaveOpen"/> is also
        /// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="MetadataReaderProvider"/>
        /// after construction.
        /// </param>
        /// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="stream"/> doesn't support read and seek operations.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception>
        /// <exception cref="IOException">Error reading from the stream (only when <see cref="MetadataStreamOptions.PrefetchMetadata"/> is specified).</exception>
        public static MetadataReaderProvider FromMetadataStream(Stream stream, MetadataStreamOptions options = MetadataStreamOptions.Default, int size = 0)
        {
            if (stream is null)
            {
                Throw.ArgumentNull(nameof(stream));
            }

            if (!stream.CanRead || !stream.CanSeek)
            {
                throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(stream));
            }

            if (!options.IsValid())
            {
                throw new ArgumentOutOfRangeException(nameof(options));
            }

            long start      = stream.Position;
            int  actualSize = StreamExtensions.GetAndValidateSize(stream, size, nameof(stream));

            MetadataReaderProvider result;
            bool closeStream = true;

            try
            {
                if ((options & MetadataStreamOptions.PrefetchMetadata) == 0)
                {
                    result      = new MetadataReaderProvider(new StreamMemoryBlockProvider(stream, start, actualSize, (options & MetadataStreamOptions.LeaveOpen) != 0));
                    closeStream = false;
                }
                else
                {
                    // Read in the entire image or metadata blob:
                    result = new MetadataReaderProvider(StreamMemoryBlockProvider.ReadMemoryBlockNoLock(stream, start, actualSize));

                    // We read all we need, the stream is going to be closed.
                }
            }
            finally
            {
                if (closeStream && (options & MetadataStreamOptions.LeaveOpen) == 0)
                {
                    stream.Dispose();
                }
            }

            return(result);
        }
Ejemplo n.º 24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="service"></param>
        /// <param name="lifetime"></param>
        /// <param name="key"></param>
        /// <param name="createimmediate"></param>
        public void Register(Type service, Func <Factory, InstanceLifetime> lifetime = null, string key = null, bool createimmediate = false)
        {
            if (null == service)
            {
                Throw.ArgumentNull(nameof(service));
            }

            var ti = service.GetTypeInfo();

            if (ti.IsAbstract || ti.IsInterface)
            {
                Throw.UnsupportedServiceType(service);
            }

            RegisterService(service, new TypeFactory(this, service), lifetime, key, createimmediate);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Encodes the type and the value of a literal.
        /// </summary>
        /// <param name="type">Called first, to encode the type of the literal.</param>
        /// <param name="scalar">Called second, to encode the value of the literal.</param>
        /// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="scalar"/> is null.</exception>
        public void TaggedScalar(Action <CustomAttributeElementTypeEncoder> type, Action <ScalarEncoder> scalar)
        {
            if (type == null)
            {
                Throw.ArgumentNull(nameof(type));
            }
            if (scalar == null)
            {
                Throw.ArgumentNull(nameof(scalar));
            }

            var parts = TaggedScalar();

            type(parts.Item1);
            scalar(parts.Item2);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Encodes an array type.
        /// </summary>
        /// <param name="elementType">Called first, to encode the type of the element.</param>
        /// <param name="arrayShape">Called second, to encode the shape of the array.</param>
        /// <exception cref="ArgumentNullException"><paramref name="elementType"/> or <paramref name="arrayShape"/> is null.</exception>
        public void Array(Action <SignatureTypeEncoder> elementType, Action <ArrayShapeEncoder> arrayShape)
        {
            if (elementType == null)
            {
                Throw.ArgumentNull(nameof(elementType));
            }
            if (arrayShape == null)
            {
                Throw.ArgumentNull(nameof(arrayShape));
            }

            var parts = Array();

            elementType(parts.Item1);
            arrayShape(parts.Item2);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Encodes Custom Attribute Signature blob.
        /// </summary>
        /// <param name="fixedArguments">Called first, to encode fixed arguments.</param>
        /// <param name="namedArguments">Called second, to encode named arguments.</param>
        /// <exception cref="ArgumentNullException"><paramref name="fixedArguments"/> or <paramref name="namedArguments"/> is null.</exception>
        public void CustomAttributeSignature(Action <FixedArgumentsEncoder> fixedArguments, Action <CustomAttributeNamedArgumentsEncoder> namedArguments)
        {
            if (fixedArguments == null)
            {
                Throw.ArgumentNull(nameof(fixedArguments));
            }
            if (namedArguments == null)
            {
                Throw.ArgumentNull(nameof(namedArguments));
            }

            var parts = CustomAttributeSignature();

            fixedArguments(parts.Item1);
            namedArguments(parts.Item2);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Encodes the type and the items of a vector literal.
        /// </summary>
        /// <param name="arrayType">Called first, to encode the type of the vector.</param>
        /// <param name="vector">Called second, to encode the items of the vector.</param>
        /// <exception cref="ArgumentNullException"><paramref name="arrayType"/> or <paramref name="vector"/> is null.</exception>
        public void TaggedVector(Action <CustomAttributeArrayTypeEncoder> arrayType, Action <VectorEncoder> vector)
        {
            if (arrayType == null)
            {
                Throw.ArgumentNull(nameof(arrayType));
            }
            if (vector == null)
            {
                Throw.ArgumentNull(nameof(vector));
            }

            var parts = TaggedVector();

            arrayType(parts.Item1);
            vector(parts.Item2);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Loads PE section of the specified name into memory and returns a memory block that spans the section.
        /// </summary>
        /// <param name="sectionName">Name of the section.</param>
        /// <returns>
        /// An empty block if no section of the given <paramref name="sectionName"/> exists in this PE image.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="sectionName"/> is null.</exception>
        /// <exception cref="InvalidOperationException">PE image not available.</exception>
        public PEMemoryBlock GetSectionData(string sectionName)
        {
            if (sectionName == null)
            {
                Throw.ArgumentNull(nameof(sectionName));
            }

            int sectionIndex = PEHeaders.IndexOfSection(sectionName);

            if (sectionIndex < 0)
            {
                return(default(PEMemoryBlock));
            }

            return(new PEMemoryBlock(GetPESectionBlock(sectionIndex)));
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Encodes return type and parameters.
        /// </summary>
        /// <param name="parameterCount">Number of parameters.</param>
        /// <param name="returnType">Called first, to encode the return type.</param>
        /// <param name="parameters">Called second, to encode the actual parameters.</param>
        /// <exception cref="ArgumentNullException"><paramref name="returnType"/> or <paramref name="parameters"/> is null.</exception>
        public void Parameters(int parameterCount, Action <ReturnTypeEncoder> returnType, Action <ParametersEncoder> parameters)
        {
            if (returnType == null)
            {
                Throw.ArgumentNull(nameof(returnType));
            }
            if (parameters == null)
            {
                Throw.ArgumentNull(nameof(parameters));
            }

            var parts = Parameters(parameterCount);

            returnType(parts.Item1);
            parameters(parts.Item2);
        }