protected void SaveVhdAndAssertContent(BlobHandle destination, FileInfo localFile, int? numThread, string storageKey, bool overwrite, bool deleteBlob, bool deleteLocal)
        {
            try
            {
                Console.WriteLine("Downloading a VHD from {0} to {1}...", destination.Blob.Uri.ToString(), localFile.FullName);
                DateTime startTime = DateTime.Now;
                VhdDownloadContext result = vmPowershellCmdlets.SaveAzureVhd(destination.Blob.Uri, localFile, numThread, storageKey, overwrite);
                Console.WriteLine("Downloading completed in {0} seconds.", (DateTime.Now - startTime).TotalSeconds);

                string calculateMd5Hash = CalculateContentMd5(File.OpenRead(result.LocalFilePath.FullName));

                Assert.IsTrue(VerifyMD5hash(destination, calculateMd5Hash));

                if (deleteBlob)
                {
                    destination.Blob.Delete();
                }

                if (deleteLocalFileIfPassed && deleteLocal)
                {
                    File.Delete(localFile.FullName);
                }
            }
            catch (Exception e)
            {
                if (deleteLocalFileIfFailed && deleteLocal)
                {
                    File.Delete(localFile.FullName);
                }
                Assert.Fail(e.InnerException.ToString());
            }
        }
        public void Initialize()
        {
            pass = true;
            testStartTime = DateTime.Now;
            storageAccountKey = vmPowershellCmdlets.GetAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccountName);  

            // Set the source blob
            blobHandle = Utilities.GetBlobHandle(vhdBlobLocation, storageAccountKey.Primary);            
        }
        private static AssemblyReferenceInformation FormatAssemblyInfo(this MetadataReader metadataReader, string name, StringHandle cultureHandle, BlobHandle publicKeyTokenHandle, Version version)
        {
            var culture = cultureHandle.IsNil
                ? "neutral"
                : metadataReader.GetString(cultureHandle);

            var publicKeyToken = publicKeyTokenHandle.IsNil
                ? "null"
                : metadataReader.FormatPublicKeyToken(publicKeyTokenHandle);

            return new AssemblyReferenceInformation(name, version, culture, publicKeyToken);
        }
 protected static void SaveVhd(BlobHandle destination, FileInfo locFile, string storageKey, int? numThread = null, bool overwrite = false)
 {
     try
     {
         Console.WriteLine("Downloading a VHD from {0} to {1}...", destination.Blob.Uri.ToString(), locFile.FullName);
         DateTime startTime = DateTime.Now;
         vmPowershellCmdlets.SaveAzureVhd(destination.Blob.Uri, locFile, numThread, storageKey, overwrite);
         Console.WriteLine("Downloading completed in {0} seconds.", (DateTime.Now - startTime).TotalSeconds);
     }
     catch (Exception e)
     {
         Assert.Fail(e.InnerException.ToString());
     }
 }
Exemple #5
0
        internal ImportDefinition(
            ImportDefinitionKind kind,
            BlobHandle alias = default(BlobHandle),
            AssemblyReferenceHandle assembly = default(AssemblyReferenceHandle),
            Handle typeOrNamespace = default(Handle))
        {
            Debug.Assert(
                typeOrNamespace.IsNil ||
                typeOrNamespace.Kind == HandleKind.Blob ||
                typeOrNamespace.Kind == HandleKind.TypeDefinition ||
                typeOrNamespace.Kind == HandleKind.TypeReference ||
                typeOrNamespace.Kind == HandleKind.TypeSpecification);

            _kind = kind;
            _alias = alias;
            _assembly = assembly;
            _typeOrNamespace = typeOrNamespace;
        }
        private BlobHandle SerializeDocumentName(string name)
        {
            Debug.Assert(name != null);

            int c1 = Count(name, s_separator1[0]);
            int c2 = Count(name, s_separator2[0]);

            char[] separator = (c1 >= c2) ? s_separator1 : s_separator2;

            // Estimate 2 bytes per part, if the blob heap gets big we expand the builder once.
            var writer = new BlobBuilder(1 + Math.Max(c1, c2) * 2);

            writer.WriteByte((byte)separator[0]);

            // TODO: avoid allocations
            foreach (var part in name.Split(separator))
            {
                BlobHandle partIndex = GetOrAddBlob(ImmutableArray.Create(MetadataWriter.s_utf8Encoding.GetBytes(part)));
                writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(partIndex));
            }

            return(GetOrAddBlob(writer));
        }
Exemple #7
0
        internal byte[] GetVirtualBlobArray(BlobHandle handle, bool unique)
        {
            BlobHandle.VirtualIndex index = handle.GetVirtualIndex();
            byte[] result = s_virtualHeapBlobs[(int)index];

            switch (index)
            {
            case BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple:
            case BlobHandle.VirtualIndex.AttributeUsage_AllowSingle:
                result = (byte[])result.Clone();
                handle.SubstituteTemplateParameters(result);
                break;

            default:
                if (unique)
                {
                    result = (byte[])result.Clone();
                }
                break;
            }

            return(result);
        }
Exemple #8
0
        internal BlobHandle GetNextHandle(BlobHandle handle)
        {
            if (handle.IsVirtual)
            {
                return(default(BlobHandle));
            }

            int offset, size;

            if (!Block.PeekHeapValueOffsetAndSize(handle.GetHeapOffset(), out offset, out size))
            {
                return(default(BlobHandle));
            }

            int nextIndex = offset + size;

            if (nextIndex >= Block.Length)
            {
                return(default(BlobHandle));
            }

            return(BlobHandle.FromOffset(nextIndex));
        }
Exemple #9
0
        public unsafe void DictionaryTryGetValue_BlobHandles()
        {
            var bHandles = new BlobHandle[m_Strings.Length];
            var bytes    = new byte[m_Strings.Length][];

            for (int i = 0; i < m_Strings.Length; i++)
            {
                var b = Encoding.ASCII.GetBytes(m_Strings[i]);
                bytes[i] = b;

                fixed(byte *bPtr = b)
                {
                    bHandles[i] = new BlobHandle(bPtr, b.Length);
                }
            }

            var bDict = new Dictionary <BlobHandle, int>(m_Strings.Length);

            for (var i = 0; i < m_Strings.Length; i++)
            {
                bDict.Add(bHandles[i], i);
            }

            // force jit compilation
            bDict.TryGetValue(bHandles[0], out var bJitValue);

            k_Stopwatch.Restart();
            foreach (var bh in bHandles)
            {
                k_Stopwatch.Start();
                bDict.TryGetValue(bh, out var value);
                k_Stopwatch.Stop();
            }
            var bTicks = k_Stopwatch.ElapsedTicks;

            WriteLog($"Dictionary.TryGetValue() w/ BlobHandle key {bTicks}");
        }
        private static RuntimeAssemblyName CreateRuntimeAssemblyNameFromMetadata(
            MetadataReader reader,
            StringHandle name,
            Version version,
            StringHandle culture,
            BlobHandle publicKeyOrToken,
            AssemblyFlags assemblyFlags)
        {
            AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None;
            if (0 != (assemblyFlags & AssemblyFlags.PublicKey))
                assemblyNameFlags |= AssemblyNameFlags.PublicKey;
            if (0 != (assemblyFlags & AssemblyFlags.Retargetable))
                assemblyNameFlags |= AssemblyNameFlags.Retargetable;
            int contentType = ((int)assemblyFlags) & 0x00000E00;
            assemblyNameFlags |= (AssemblyNameFlags)contentType;

            return new RuntimeAssemblyName(
                name.GetString(reader),
                version,
                culture.GetString(reader),
                assemblyNameFlags,
                reader.GetBlobContent(publicKeyOrToken).ToArray()
                );
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"></see> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
        /// <contract>
        ///   <requires name="e" condition="not null" />
        /// </contract>
        protected override void OnLoad([NotNull] EventArgs e)
        {
            Assert.ArgumentNotNull(e, "e");

            base.OnLoad(e);

            string blobHandle = WebUtil.GetQueryString("blob");

            if (!string.IsNullOrEmpty(blobHandle))
            {
                var blobName = BlobHandle.GetBlobName(blobHandle);

                if (!string.IsNullOrEmpty(blobName))
                {
                    var blob     = LogStorageManager.GetBlob(blobName);
                    var response = HttpContext.Current.Response;

                    using (var stream = new MemoryStream())
                    {
                        blob.DownloadToStream(stream);

                        response.ClearHeaders();
                        response.ContentType = blob.Properties.ContentType;

                        response.AddHeader("Content-Disposition", "attachment; filename=\"" + blob.Name + "\"");
                        response.AddHeader("Content-Length", blob.Properties.Length.ToString(CultureInfo.InvariantCulture));

                        response.AddHeader("Content-Transfer-Encoding", "binary");
                        response.CacheControl = "private";

                        response.BinaryWrite(stream.ToArray());
                        response.End();
                    }
                }
            }
        }
        public LocalConstantHandle AddLocalConstant(StringHandle name, BlobHandle signature)
        {
            _localConstantTable.Add(new LocalConstantRow
            {
                Name = name,
                Signature = signature
            });

            return MetadataTokens.LocalConstantHandle(_localConstantTable.Count);
        }
 public void AddCustomDebugInformation(EntityHandle parent, GuidHandle kind, BlobHandle value)
 {
     _customDebugInformationTable.Add(new CustomDebugInformationRow
     {
         Parent = (uint)CodedIndex.ToHasCustomDebugInformation(parent),
         Kind = kind,
         Value = value
     });
 }
 public void AddAssemblyFile(
     StringHandle name,
     BlobHandle hashValue,
     bool containsMetadata)
 {
     _fileTable.Add(new FileTableRow
     {
         FileName = name,
         Flags = containsMetadata ? 0u : 1u,
         HashValue = hashValue
     });
 }
        public DocumentHandle AddDocument(BlobHandle name, GuidHandle hashAlgorithm, BlobHandle hash, GuidHandle language)
        {
            _documentTable.Add(new DocumentRow
            {
                Name = name,
                HashAlgorithm = hashAlgorithm,
                Hash = hash,
                Language = language
            });

            return MetadataTokens.DocumentHandle(_documentTable.Count);
        }
Exemple #16
0
        /// <exception cref="BadImageFormatException">An exception from metadata reader.</exception>
        private static AssemblyIdentity CreateAssemblyIdentityOrThrow(
            this MetadataReader reader,
            Version version,
            AssemblyFlags flags,
            BlobHandle publicKey,
            StringHandle name,
            StringHandle culture,
            bool isReference)
        {
            string nameStr = reader.GetString(name);

            if (!MetadataHelpers.IsValidMetadataIdentifier(nameStr))
            {
                throw new BadImageFormatException(string.Format(CodeAnalysisResources.InvalidAssemblyName, nameStr));
            }

            string cultureName = culture.IsNil ? null : reader.GetString(culture);

            if (cultureName != null && !MetadataHelpers.IsValidMetadataIdentifier(cultureName))
            {
                throw new BadImageFormatException(string.Format(CodeAnalysisResources.InvalidCultureName, cultureName));
            }

            ImmutableArray <byte> publicKeyOrToken = reader.GetBlobContent(publicKey);
            bool hasPublicKey;

            if (isReference)
            {
                hasPublicKey = (flags & AssemblyFlags.PublicKey) != 0;
                if (hasPublicKey)
                {
                    if (!MetadataHelpers.IsValidPublicKey(publicKeyOrToken))
                    {
                        throw new BadImageFormatException(CodeAnalysisResources.InvalidPublicKey);
                    }
                }
                else
                {
                    if (!publicKeyOrToken.IsEmpty &&
                        publicKeyOrToken.Length != AssemblyIdentity.PublicKeyTokenSize)
                    {
                        throw new BadImageFormatException(CodeAnalysisResources.InvalidPublicKeyToken);
                    }
                }
            }
            else
            {
                // Assembly definitions never contain a public key token, they only can have a full key or nothing,
                // so the flag AssemblyFlags.PublicKey does not make sense for them and is ignored.
                // See Ecma-335, Partition II Metadata, 22.2 "Assembly : 0x20".
                // This also corresponds to the behavior of the native C# compiler and sn.exe tool.
                hasPublicKey = !publicKeyOrToken.IsEmpty;
                if (hasPublicKey && !MetadataHelpers.IsValidPublicKey(publicKeyOrToken))
                {
                    throw new BadImageFormatException(CodeAnalysisResources.InvalidPublicKey);
                }
            }

            if (publicKeyOrToken.IsEmpty)
            {
                publicKeyOrToken = default(ImmutableArray <byte>);
            }

            return(new AssemblyIdentity(
                       name: nameStr,
                       version: version,
                       cultureName: cultureName,
                       publicKeyOrToken: publicKeyOrToken,
                       hasPublicKey: hasPublicKey,
                       isRetargetable: (flags & AssemblyFlags.Retargetable) != 0,
                       contentType: (AssemblyContentType)((int)(flags & AssemblyFlags.ContentTypeMask) >> 9),
                       noThrow: true));
        }
        public MethodDefinitionHandle AddMethodDefinition(
            MethodAttributes attributes, 
            MethodImplAttributes implAttributes,
            StringHandle name,
            BlobHandle signature,
            int bodyOffset,
            ParameterHandle paramList)
        {
            _methodDefTable.Add(new MethodRow
            {
                Flags = (ushort)attributes,
                ImplFlags = (ushort)implAttributes,
                Name = name,
                Signature = signature,
                BodyOffset = bodyOffset,
                ParamList = (uint)MetadataTokens.GetRowNumber(paramList)
            });

            return MetadataTokens.MethodDefinitionHandle(_methodDefTable.Count);
        }
 public byte[] GetBlobBytes(BlobHandle handle)
 {
     return BlobHeap.GetBytes(handle);
 }
Exemple #19
0
 public BlobReader GetBlobReader(BlobHandle handle)
 {
     return BlobStream.GetBlobReader(handle);
 }
Exemple #20
0
        /// <summary>
        /// Used to validate metadata blobs emitted for MarshalAs.
        /// </summary>
        internal static void MarshalAsMetadataValidator(PEAssembly assembly, Func <string, PEAssembly, TestEmitters, byte[]> getExpectedBlob, TestEmitters emitOptions, bool isField = true)
        {
            var metadataReader = assembly.GetMetadataReader();

            // no custom attributes should be emitted on parameters, fields or methods:
            foreach (var ca in metadataReader.CustomAttributes)
            {
                Assert.NotEqual("MarshalAsAttribute", GetAttributeName(metadataReader, ca));
            }

            int expectedMarshalCount = 0;

            if (isField)
            {
                // fields
                foreach (var fieldDef in metadataReader.FieldDefinitions)
                {
                    var    field     = metadataReader.GetFieldDefinition(fieldDef);
                    string fieldName = metadataReader.GetString(field.Name);

                    byte[] expectedBlob = getExpectedBlob(fieldName, assembly, emitOptions);
                    if (expectedBlob != null)
                    {
                        BlobHandle descriptor = metadataReader.GetFieldDefinition(fieldDef).GetMarshallingDescriptor();
                        Assert.False(descriptor.IsNil, "Expecting record in FieldMarshal table");

                        Assert.NotEqual(0, (int)(field.Attributes & FieldAttributes.HasFieldMarshal));
                        expectedMarshalCount++;

                        byte[] actualBlob = metadataReader.GetBlobBytes(descriptor);
                        AssertEx.Equal(expectedBlob, actualBlob);
                    }
                    else
                    {
                        Assert.Equal(0, (int)(field.Attributes & FieldAttributes.HasFieldMarshal));
                    }
                }
            }
            else
            {
                // parameters
                foreach (var methodHandle in metadataReader.MethodDefinitions)
                {
                    var    methodDef  = metadataReader.GetMethodDefinition(methodHandle);
                    string memberName = metadataReader.GetString(methodDef.Name);
                    foreach (var paramHandle in methodDef.GetParameters())
                    {
                        var    paramRow  = metadataReader.GetParameter(paramHandle);
                        string paramName = metadataReader.GetString(paramRow.Name);

                        byte[] expectedBlob = getExpectedBlob(memberName + ":" + paramName, assembly, emitOptions);
                        if (expectedBlob != null)
                        {
                            Assert.NotEqual(0, (int)(paramRow.Attributes & ParameterAttributes.HasFieldMarshal));
                            expectedMarshalCount++;

                            BlobHandle descriptor = metadataReader.GetParameter(paramHandle).GetMarshallingDescriptor();
                            Assert.False(descriptor.IsNil, "Expecting record in FieldMarshal table");

                            byte[] actualBlob = metadataReader.GetBlobBytes(descriptor);

                            AssertEx.Equal(expectedBlob, actualBlob);
                        }
                        else
                        {
                            Assert.Equal(0, (int)(paramRow.Attributes & ParameterAttributes.HasFieldMarshal));
                        }
                    }
                }
            }

            Assert.Equal(expectedMarshalCount, metadataReader.GetTableRowCount(TableIndex.FieldMarshal));
        }
 internal byte[] GetVirtualBlobBytes(BlobHandle handle, bool unique)
 {
     BlobHandle.VirtualIndex index = handle.GetVirtualIndex();
     byte[] result = s_virtualValues ![(int)index];
        private void AssertContentMD5(string destination, bool deleteBlob)
        {
            string downloadedFile = DownloadToFile(destination);

            var calculateMd5Hash = CalculateContentMd5(File.OpenRead(downloadedFile));

            BlobUri blobUri2;
            Assert.IsTrue(BlobUri.TryParseUri(new Uri(destination), out blobUri2));
            var blobHandle = new BlobHandle(blobUri2, storageAccountKey.Primary);

            Assert.AreEqual(calculateMd5Hash, blobHandle.Blob.Properties.ContentMD5);

            if (deleteBlob)
            {
                blobHandle.Blob.Delete();
            }
        }
Exemple #23
0
        internal static ImmutableArray <CilType> DecodeMethodSpecificationSignature(BlobHandle handle, CilTypeProvider provider)
        {
            var blobReader = provider.Reader.GetBlobReader(handle);

            return(NewDecoder(provider).DecodeMethodSpecificationSignature(ref blobReader));
        }
Exemple #24
0
        internal static CilType DecodeFieldSignature(BlobHandle handle, CilTypeProvider provider)
        {
            var blobReader = provider.Reader.GetBlobReader(handle);

            return(NewDecoder(provider).DecodeFieldSignature(ref blobReader));
        }
Exemple #25
0
 protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex)
 {
     return(MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex)));
 }
 public BlobReader GetBlobReader(BlobHandle handle)
 {
     return BlobHeap.GetBlobReader(handle);
 }
Exemple #27
0
        private static string FormatPublicKeyToken(this MetadataReader metadataReader, BlobHandle handle)
        {
            byte[] bytes = metadataReader.GetBlobBytes(handle);

            if (bytes == null || bytes.Length <= 0)
            {
                return("null");
            }

            if (bytes.Length > 8)  // Strong named assembly
            {
                // Get the public key token, which is the last 8 bytes of the SHA-1 hash of the public key
                using (var sha1 = SHA1.Create())
                {
                    var token = sha1.ComputeHash(bytes);

                    bytes = new byte[8];
                    int count = 0;
                    for (int i = token.Length - 1; i >= token.Length - 8; i--)
                    {
                        bytes[count] = token[i];
                        count++;
                    }
                }
            }

            // Convert bytes to string, but we don't want the '-' characters and need it to be lower case
            return(BitConverter.ToString(bytes)
                   .Replace("-", "")
                   .ToLowerInvariant());
        }
Exemple #28
0
 internal int SerializeHandle(BlobHandle handle) => handle.GetHeapOffset();
Exemple #29
0
        public long GetBytes(int i, ColumnData[] columns, long fieldOffset,
                             byte[] buffer, int bufferOffset, int length)
        {
            ColumnData column = columns[i];
            object     data   = currentRow[i + 1];

            if (data is BlobHandle)
            {
                BlobHandle blob = (BlobHandle)data;
                if (buffer == null)
                {
                    return(blob.length < fieldOffset ? 0 : blob.length - fieldOffset);
                }
                if (fieldOffset < column.lobOffset)
                {
                    blob.Rewind();
                    column.lobOffset = 0;
                }
                if (fieldOffset > column.lobOffset)
                {
                    GetData(column, blob, (int)(fieldOffset - column.lobOffset), null, 0);
                    if (fieldOffset > column.lobOffset)
                    {
                        return(0);
                    }
                }
                return(GetData(column, blob, length, buffer, bufferOffset));
            }
            else if (data is byte[])
            {
                byte[] bytes = (byte[])data;
                if (buffer == null)
                {
                    return(bytes.Length < fieldOffset ? 0 : bytes.Length - fieldOffset);
                }
                if (length > (bytes.Length - fieldOffset))
                {
                    length = (int)(bytes.Length - fieldOffset);
                }
                Array.Copy(bytes, (int)fieldOffset, buffer, bufferOffset, length);
                return(length);
            }
            else if (data is string)
            {
                string str = (string)data;
                if (buffer == null)
                {
                    return(str.Length < fieldOffset ? 0 : str.Length - fieldOffset);
                }
                if (length > (str.Length - fieldOffset))
                {
                    length = (int)(str.Length - fieldOffset);
                }
                BufferTypeBinary.ConvertStringToBytes(str, buffer,
                                                      bufferOffset, length,
                                                      (int)fieldOffset);
                return(length);
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Exemple #30
0
 public BlobHeapEntry(MetadataReader metadata, BlobHandle handle)
 {
     this.metadata = metadata;
     this.handle   = handle;
 }
        public void AddMarshallingDescriptor(
            EntityHandle parent,
            BlobHandle descriptor)
        {
            uint codedIndex = (uint)CodedIndex.ToHasFieldMarshal(parent);

            // the table is required to be sorted by Parent:
            _fieldMarshalTableNeedsSorting |= codedIndex < _fieldMarshalTableLastParent;
            _fieldMarshalTableLastParent = codedIndex;

            _fieldMarshalTable.Add(new FieldMarshalRow
            {
                Parent = codedIndex,
                NativeType = descriptor
            });
        }
        private static string ReadUtf8String(MetadataReader reader, BlobHandle handle)
        {
            var bytes = reader.GetBlobBytes(handle);

            return(Encoding.UTF8.GetString(bytes, 0, bytes.Length));
        }
        public MemberReferenceHandle AddMemberReference(
            EntityHandle parent,
            StringHandle name,
            BlobHandle signature)
        {
            _memberRefTable.Add(new MemberRefRow
            {
                Class = (uint)CodedIndex.ToMemberRefParent(parent),
                Name = name,
                Signature = signature
            });

            return MetadataTokens.MemberReferenceHandle(_memberRefTable.Count);
        }
        public int GetHeapOffset(BlobHandle handle)
        {
            int offset = MetadataTokens.GetHeapOffset(handle);

            return((offset == 0) ? 0 : _blobHeapStartOffset + offset);
        }
        public void AddDeclarativeSecurityAttribute(
            EntityHandle parent,
            DeclarativeSecurityAction action,
            BlobHandle permissionSet)
        {
            uint parentCodedIndex = (uint)CodedIndex.ToHasDeclSecurity(parent);

            // the table is required to be sorted by Parent:
            _declSecurityTableNeedsSorting |= parentCodedIndex < _declSecurityTableLastParent;
            _declSecurityTableLastParent = parentCodedIndex;

            _declSecurityTable.Add(new DeclSecurityRow
            {
                Parent = parentCodedIndex,
                Action = (ushort)action,
                PermissionSet = permissionSet
            });
        }
Exemple #36
0
 private string Literal(BlobHandle handle)
 {
     return(Literal(handle, (r, h) => BitConverter.ToString(r.GetBytes((BlobHandle)h))));
 }
 public void AddMethodDebugInformation(DocumentHandle document, BlobHandle sequencePoints)
 {
     _methodDebugInformationTable.Add(new MethodDebugInformationRow
     {
         Document = (uint)MetadataTokens.GetRowNumber(document),
         SequencePoints = sequencePoints
     });
 }
        internal BlobHandle GetSignature(LocalConstantHandle handle)
        {
            int rowOffset = (handle.RowId - 1) * RowSize;

            return(BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _signatureOffset, _isBlobHeapRefSizeSmall)));
        }
        public ImportScopeHandle AddImportScope(ImportScopeHandle parentScope, BlobHandle imports)
        {
            _importScopeTable.Add(new ImportScopeRow
            {
                Parent = (uint)MetadataTokens.GetRowNumber(parentScope),
                Imports = imports
            });

            return MetadataTokens.ImportScopeHandle(_importScopeTable.Count);
        }
        internal BlobHandle GetValue(CustomDebugInformationHandle handle)
        {
            int rowOffset = (handle.RowId - 1) * RowSize;

            return(BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _valueOffset, _isBlobHeapRefSizeSmall)));
        }
        public static void Convert(Stream peStream, Stream sourcePdbStream, Stream targetPdbStream)
        {
            var metadataBuilder = new MetadataBuilder();
            ImmutableArray <int> typeSystemRowCounts;
            var debugEntryPointToken = default(MethodDefinitionHandle);
            var pdbId = default(BlobContentId);

            try
            {
                using (var peReader = new PEReader(peStream))
                {
                    pdbId = ReadPdbId(peReader);

                    var symReader = SymReaderFactory.CreateWindowsPdbReader(sourcePdbStream, peReader);

                    var metadataReader = peReader.GetMetadataReader();
                    var metadataModel  = new MetadataModel(metadataReader);

                    typeSystemRowCounts  = metadataModel.GetRowCounts();
                    debugEntryPointToken = ReadEntryPointHandle(symReader);

                    // documents:
                    var documentIndex = new Dictionary <string, DocumentHandle>(StringComparer.Ordinal);
                    var documents     = symReader.GetDocuments();
                    metadataBuilder.SetCapacity(TableIndex.Document, documents.Length);

                    bool vbSemantics = false;

                    foreach (var document in documents)
                    {
                        string name     = document.GetName();
                        Guid   language = document.GetLanguage();

                        // TODO:
                        // won't work for IL-merged assmemblies
                        vbSemantics |= language == SymReaderHelpers.VisualBasicLanguageGuid;

                        var rid = metadataBuilder.AddDocument(
                            name: metadataBuilder.GetOrAddDocumentName(name),
                            hashAlgorithm: metadataBuilder.GetOrAddGuid(document.GetHashAlgorithm()),
                            hash: metadataBuilder.GetOrAddBlob(document.GetChecksum()),
                            language: metadataBuilder.GetOrAddGuid(language));

                        documentIndex.Add(name, rid);
                    }

                    var lastLocalVariableHandle = default(LocalVariableHandle);
                    var lastLocalConstantHandle = default(LocalConstantHandle);

                    var importStringsByMethod = new Dictionary <int, ImmutableArray <string> >();
                    var importScopesByMethod  = new Dictionary <int, ImportScopeHandle>();

                    // Maps import scope content to import scope handles
                    var importScopeIndex = new Dictionary <ImportScopeInfo, ImportScopeHandle>();
                    var importScopes     = new List <ImportScopeInfo>();

                    // reserve slot for module import scope:
                    importScopes.Add(default(ImportScopeInfo));

                    var externAliasImports   = new List <ImportInfo>();
                    var externAliasStringSet = new HashSet <string>(StringComparer.Ordinal);

                    string vbDefaultNamespace    = null;
                    var    vbProjectLevelImports = new List <ImportInfo>();

                    // first pass:
                    foreach (var methodHandle in metadataReader.MethodDefinitions)
                    {
                        int methodToken = MetadataTokens.GetToken(methodHandle);
                        ImmutableArray <ImmutableArray <ImportInfo> > importGroups;

                        if (vbSemantics)
                        {
                            var importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings(
                                methodToken,
                                symReader,
                                getMethodImportStrings: (token, sr) => GetImportStrings(token, importStringsByMethod, sr));

                            if (importStrings.IsEmpty)
                            {
                                // no debug info
                                continue;
                            }

                            var vbFileLevelImports = ArrayBuilder <ImportInfo> .GetInstance();

                            foreach (var importString in importStrings)
                            {
                                if (TryParseImportString(importString, out var import, vbSemantics: true))
                                {
                                    if (import.Kind == ImportTargetKind.DefaultNamespace)
                                    {
                                        vbDefaultNamespace = import.Target;
                                    }
                                    else if (import.Scope == VBImportScopeKind.Project)
                                    {
                                        vbProjectLevelImports.Add(import);
                                    }
                                    else
                                    {
                                        vbFileLevelImports.Add(import);
                                    }
                                }
                            }

                            importGroups = ImmutableArray.Create(vbFileLevelImports.ToImmutableAndFree());
                        }
                        else
                        {
                            var importStringGroups = CustomDebugInfoReader.GetCSharpGroupedImportStrings(
                                methodToken,
                                symReader,
                                getMethodCustomDebugInfo: (token, sr) => sr.GetCustomDebugInfo(token, methodVersion: 1),
                                getMethodImportStrings: (token, sr) => GetImportStrings(token, importStringsByMethod, sr),
                                externAliasStrings: out var localExternAliasStrings);

                            if (importStringGroups.IsDefault)
                            {
                                // no debug info
                                continue;
                            }

                            if (!localExternAliasStrings.IsDefault)
                            {
                                foreach (var externAlias in localExternAliasStrings)
                                {
                                    if (externAliasStringSet.Add(externAlias) &&
                                        TryParseImportString(externAlias, out var import, vbSemantics: false))
                                    {
                                        externAliasImports.Add(import);
                                    }
                                }
                            }

                            importGroups = ImmutableArray.CreateRange(importStringGroups.Select(g => ParseImportStrings(g, vbSemantics: false)));
                        }

                        var importScopeHandle = DefineImportScope(importGroups, importScopeIndex, importScopes);
                        importScopesByMethod.Add(methodToken, importScopeHandle);
                    }

                    // import scopes:
                    metadataBuilder.AddImportScope(
                        parentScope: default(ImportScopeHandle),
                        imports: SerializeModuleImportScope(metadataBuilder, externAliasImports, vbProjectLevelImports, vbDefaultNamespace, metadataModel));

                    for (int i = 1; i < importScopes.Count; i++)
                    {
                        metadataBuilder.AddImportScope(
                            parentScope: importScopes[i].Parent,
                            imports: SerializeImportsBlob(metadataBuilder, importScopes[i].Imports, metadataModel));
                    }

                    var dynamicNames = new Dictionary <string, DynamicLocalInfo>();
                    var dynamicSlots = new Dictionary <int, DynamicLocalInfo>();

                    // methods:
                    metadataBuilder.SetCapacity(TableIndex.MethodDebugInformation, metadataReader.MethodDefinitions.Count);
                    foreach (var methodHandle in metadataReader.MethodDefinitions)
                    {
                        var methodDef   = metadataReader.GetMethodDefinition(methodHandle);
                        int methodToken = MetadataTokens.GetToken(methodHandle);

                        var symMethod = symReader.GetMethod(methodToken);
                        if (symMethod == null)
                        {
                            metadataBuilder.AddMethodDebugInformation(default(DocumentHandle), sequencePoints: default(BlobHandle));
                            continue;
                        }

                        // method debug info:
                        int localSignatureRowId;
                        if (methodDef.RelativeVirtualAddress != 0)
                        {
                            var methodBody = peReader.GetMethodBody(methodDef.RelativeVirtualAddress);
                            localSignatureRowId = methodBody.LocalSignature.IsNil ? 0 : MetadataTokens.GetRowNumber(methodBody.LocalSignature);
                        }
                        else
                        {
                            localSignatureRowId = 0;
                        }

                        var symSequencePoints = symMethod.GetSequencePoints().ToImmutableArray();

                        DocumentHandle singleDocumentHandle;
                        BlobHandle     sequencePointsBlob = SerializeSequencePoints(metadataBuilder, localSignatureRowId, symSequencePoints, documentIndex, out singleDocumentHandle);

                        metadataBuilder.AddMethodDebugInformation(
                            document: singleDocumentHandle,
                            sequencePoints: sequencePointsBlob);

                        // state machine and async info:
                        var symAsyncMethod = symMethod.AsAsyncMethod();
                        if (symAsyncMethod != null)
                        {
                            var kickoffToken = MetadataTokens.Handle(symAsyncMethod.GetKickoffMethod());
                            metadataBuilder.AddStateMachineMethod(
                                moveNextMethod: methodHandle,
                                kickoffMethod: (MethodDefinitionHandle)kickoffToken);

                            metadataBuilder.AddCustomDebugInformation(
                                parent: methodHandle,
                                kind: metadataBuilder.GetOrAddGuid(PortableCustomDebugInfoKinds.AsyncMethodSteppingInformationBlob),
                                value: SerializeAsyncMethodSteppingInfo(metadataBuilder, symAsyncMethod, MetadataTokens.GetRowNumber(methodHandle)));
                        }

                        // custom debug information:
                        var dynamicLocals = default(ImmutableArray <DynamicLocalInfo>);

                        byte[] customDebugInfoBytes = symReader.GetCustomDebugInfo(methodToken, methodVersion: 1);
                        if (customDebugInfoBytes != null)
                        {
                            foreach (var record in CustomDebugInfoReader.GetCustomDebugInfoRecords(customDebugInfoBytes))
                            {
                                switch (record.Kind)
                                {
                                case CustomDebugInfoKind.DynamicLocals:
                                    dynamicLocals = CustomDebugInfoReader.DecodeDynamicLocalsRecord(record.Data);
                                    break;

                                case CustomDebugInfoKind.StateMachineHoistedLocalScopes:
                                    metadataBuilder.AddCustomDebugInformation(
                                        parent: methodHandle,
                                        kind: metadataBuilder.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLocalSlotMap),
                                        value: SerializeStateMachineHoistedLocalsBlob(metadataBuilder, CustomDebugInfoReader.DecodeStateMachineHoistedLocalScopesRecord(record.Data)));
                                    break;

                                case CustomDebugInfoKind.EditAndContinueLocalSlotMap:
                                    metadataBuilder.AddCustomDebugInformation(
                                        parent: methodHandle,
                                        kind: metadataBuilder.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLocalSlotMap),
                                        value: metadataBuilder.GetOrAddBlob(record.Data));
                                    break;

                                case CustomDebugInfoKind.EditAndContinueLambdaMap:
                                    metadataBuilder.AddCustomDebugInformation(
                                        parent: methodHandle,
                                        kind: metadataBuilder.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap),
                                        value: metadataBuilder.GetOrAddBlob(record.Data));
                                    break;
                                }
                            }
                        }

                        var rootScope = symMethod.GetRootScope();
                        if (rootScope.GetNamespaces().Length == 0 || rootScope.GetLocals().Length == 0 || rootScope.GetConstants().Length == 0)
                        {
                            dynamicNames.Clear();
                            dynamicSlots.Clear();

                            foreach (var dynamicLocal in dynamicLocals)
                            {
                                if (dynamicLocal.SlotId == 0)
                                {
                                    // All dynamic constants have slot id == 0,
                                    // but a variable can also have slot id == 0
                                    if (!dynamicNames.ContainsKey(dynamicLocal.LocalName))
                                    {
                                        dynamicNames.Add(dynamicLocal.LocalName, dynamicLocal);
                                    }
                                    else
                                    {
                                        // TODO: warning
                                    }
                                }
                                else if (!dynamicSlots.ContainsKey(dynamicLocal.SlotId))
                                {
                                    dynamicSlots.Add(dynamicLocal.SlotId, dynamicLocal);
                                }
                                else
                                {
                                    // TODO: warning
                                }
                            }

                            foreach (ISymUnmanagedScope scope in rootScope.GetChildren())
                            {
                                SerializeScope(
                                    metadataBuilder,
                                    metadataModel,
                                    methodHandle,
                                    importScopesByMethod[methodToken],
                                    scope,
                                    dynamicSlots,
                                    dynamicNames,
                                    vbSemantics,
                                    ref lastLocalVariableHandle,
                                    ref lastLocalConstantHandle);
                            }
                        }
                        else
                        {
                            // TODO: warning:
                            // "Root scope must be empty (method 0x{0:x8})", MetadataTokens.GetToken(methodHandle))
                        }
                    }
                }
            }
            catch (COMException e)
            {
                // TODO: loc
                throw new BadImageFormatException("Invalid PDB format: " + e.Message, e);
            }

            var         serializer  = new PortablePdbBuilder(metadataBuilder, typeSystemRowCounts, debugEntryPointToken, idProvider: _ => pdbId);
            BlobBuilder blobBuilder = new BlobBuilder();

            serializer.Serialize(blobBuilder);
            blobBuilder.WriteContentTo(targetPdbStream);
        }
Exemple #42
0
 public byte[] GetBlobBytes(BlobHandle handle)
 {
     return BlobStream.GetBytes(handle);
 }
        private void SerializeMethodDebugInfo(IMethodBody bodyOpt, int methodRid, StandaloneSignatureHandle localSignatureHandleOpt, ref LocalVariableHandle lastLocalVariableHandle, ref LocalConstantHandle lastLocalConstantHandle)
        {
            if (bodyOpt == null)
            {
                _debugMetadataOpt.AddMethodDebugInformation(default(DocumentHandle), default(BlobHandle));
                return;
            }

            bool isIterator    = bodyOpt.StateMachineTypeName != null;
            bool emitDebugInfo = isIterator || bodyOpt.HasAnySequencePoints;

            if (!emitDebugInfo)
            {
                _debugMetadataOpt.AddMethodDebugInformation(default(DocumentHandle), default(BlobHandle));
                return;
            }

            var methodHandle = MetadataTokens.MethodDefinitionHandle(methodRid);

            var bodyImportScope   = bodyOpt.ImportScope;
            var importScopeHandle = (bodyImportScope != null) ? GetImportScopeIndex(bodyImportScope, _scopeIndex) : default(ImportScopeHandle);

            // documents & sequence points:
            DocumentHandle singleDocumentHandle;
            ArrayBuilder <Cci.SequencePoint> sequencePoints = ArrayBuilder <Cci.SequencePoint> .GetInstance();

            bodyOpt.GetSequencePoints(sequencePoints);
            BlobHandle sequencePointsBlob = SerializeSequencePoints(localSignatureHandleOpt, sequencePoints.ToImmutableAndFree(), _documentIndex, out singleDocumentHandle);

            _debugMetadataOpt.AddMethodDebugInformation(document: singleDocumentHandle, sequencePoints: sequencePointsBlob);

            // Unlike native PDB we don't emit an empty root scope.
            // scopes are already ordered by StartOffset ascending then by EndOffset descending (the longest scope first).

            if (bodyOpt.LocalScopes.Length == 0)
            {
                // TODO: the compiler should produce a scope for each debuggable method
                _debugMetadataOpt.AddLocalScope(
                    method: methodHandle,
                    importScope: importScopeHandle,
                    variableList: NextHandle(lastLocalVariableHandle),
                    constantList: NextHandle(lastLocalConstantHandle),
                    startOffset: 0,
                    length: bodyOpt.IL.Length);
            }
            else
            {
                foreach (LocalScope scope in bodyOpt.LocalScopes)
                {
                    _debugMetadataOpt.AddLocalScope(
                        method: methodHandle,
                        importScope: importScopeHandle,
                        variableList: NextHandle(lastLocalVariableHandle),
                        constantList: NextHandle(lastLocalConstantHandle),
                        startOffset: scope.StartOffset,
                        length: scope.Length);

                    foreach (ILocalDefinition local in scope.Variables)
                    {
                        Debug.Assert(local.SlotIndex >= 0);

                        lastLocalVariableHandle = _debugMetadataOpt.AddLocalVariable(
                            attributes: local.PdbAttributes,
                            index: local.SlotIndex,
                            name: _debugMetadataOpt.GetOrAddString(local.Name));

                        SerializeLocalInfo(local, lastLocalVariableHandle);
                    }

                    foreach (ILocalDefinition constant in scope.Constants)
                    {
                        var mdConstant = constant.CompileTimeValue;
                        Debug.Assert(mdConstant != null);

                        lastLocalConstantHandle = _debugMetadataOpt.AddLocalConstant(
                            name: _debugMetadataOpt.GetOrAddString(constant.Name),
                            signature: SerializeLocalConstantSignature(constant));

                        SerializeLocalInfo(constant, lastLocalConstantHandle);
                    }
                }
            }

            var asyncDebugInfo = bodyOpt.AsyncDebugInfo;

            if (asyncDebugInfo != null)
            {
                _debugMetadataOpt.AddStateMachineMethod(
                    moveNextMethod: methodHandle,
                    kickoffMethod: GetMethodDefinitionHandle(asyncDebugInfo.KickoffMethod));

                SerializeAsyncMethodSteppingInfo(asyncDebugInfo, methodHandle);
            }

            SerializeStateMachineLocalScopes(bodyOpt, methodHandle);

            // delta doesn't need this information - we use information recorded by previous generation emit
            if (Context.Module.CommonCompilation.Options.EnableEditAndContinue && !IsFullMetadata)
            {
                SerializeEncMethodDebugInformation(bodyOpt, methodHandle);
            }
        }
Exemple #44
0
        private static AssemblyReferenceInformation FormatAssemblyInfo(this MetadataReader metadataReader, string name, StringHandle cultureHandle, BlobHandle publicKeyTokenHandle, Version version)
        {
            var culture = cultureHandle.IsNil
                ? "neutral"
                : metadataReader.GetString(cultureHandle);

            var publicKeyToken = publicKeyTokenHandle.IsNil
                ? "null"
                : metadataReader.FormatPublicKeyToken(publicKeyTokenHandle);

            return(new AssemblyReferenceInformation(name, version, culture, publicKeyToken));
        }
Exemple #45
0
 private BlobHandle ImportValue(BlobHandle src) => _builder.GetOrAddBlob(_reader.GetBlobContent(src));
 public void AddAssembly(
     StringHandle name, 
     Version version,
     StringHandle culture,
     BlobHandle publicKey,
     AssemblyFlags flags,
     AssemblyHashAlgorithm hashAlgorithm)
 {
     _assemblyTable.Add(new AssemblyRow
     {
         Flags = (ushort)flags,
         HashAlgorithm = (uint)hashAlgorithm,
         Version = version,
         AssemblyKey = publicKey,
         AssemblyName = name,
         AssemblyCulture = culture
     });
 }
Exemple #47
0
 internal BlobReader GetBlobReader(BlobHandle handle)
 {
     return(new BlobReader(GetMemoryBlock(handle)));
 }
        public AssemblyReferenceHandle AddAssemblyReference(
            StringHandle name,
            Version version,
            StringHandle culture,
            BlobHandle publicKeyOrToken,
            AssemblyFlags flags,
            BlobHandle hashValue)
        {
            _assemblyRefTable.Add(new AssemblyRefTableRow
            {
                Name = name,
                Version = version,
                Culture = culture,
                PublicKeyToken = publicKeyOrToken,
                Flags = (uint)flags,
                HashValue = hashValue
            });

            return MetadataTokens.AssemblyReferenceHandle(_assemblyRefTable.Count);
        }
        internal BlobHandle GetSequencePoints(MethodDebugInformationHandle handle)
        {
            int rowOffset = (handle.RowId - 1) * RowSize;

            return(BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _sequencePointsOffset, _isBlobHeapRefSizeSmall)));
        }
 public void AddTypeSpecification(BlobHandle signature)
 {
     _typeSpecTable.Add(new TypeSpecRow
     {
         Signature = signature
     });
 }
        internal BlobHandle GetImports(ImportScopeHandle handle)
        {
            int rowOffset = (handle.RowId - 1) * RowSize;

            return(BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _importsOffset, _isBlobHeapRefSizeSmall)));
        }
 public void AddStandaloneSignature(BlobHandle signature)
 {
     _standAloneSigTable.Add(new StandaloneSigRow
     {
         Signature = signature
     });
 }
        internal BlobHandle GetHash(DocumentHandle handle)
        {
            int rowOffset = (handle.RowId - 1) * RowSize;

            return(BlobHandle.FromOffset(Block.PeekHeapReference(rowOffset + _hashOffset, _isBlobHeapRefSizeSmall)));
        }
 public void AddProperty(PropertyAttributes attributes, StringHandle name, BlobHandle signature)
 {
     _propertyTable.Add(new PropertyRow
     {
         PropFlags = (ushort)attributes,
         Name = name,
         Type = signature
     });
 }
Exemple #55
0
 public ImmutableArray<byte> GetBlobContent(BlobHandle handle)
 {
     // TODO: We can skip a copy for virtual blobs.
     byte[] bytes = GetBlobBytes(handle);
     return ImmutableArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes);
 }
        public void AddCustomAttribute(EntityHandle parent, EntityHandle constructor, BlobHandle value)
        {
            uint parentCodedIndex = (uint)CodedIndex.ToHasCustomAttribute(parent);

            // the table is required to be sorted by Parent:
            _customAttributeTableNeedsSorting |= parentCodedIndex < _customAttributeTableLastParent;
            _customAttributeTableLastParent = parentCodedIndex;

            _customAttributeTable.Add(new CustomAttributeRow
            {
                Parent = parentCodedIndex,
                Type = (uint)CodedIndex.ToCustomAttributeType(constructor),
                Value = value
            });
        }
Exemple #57
0
        public void IsNil()
        {
            Assert.False(ModuleDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(AssemblyDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(InterfaceImplementationHandle.FromRowId(1).IsNil);
            Assert.False(MethodDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(MethodSpecificationHandle.FromRowId(1).IsNil);
            Assert.False(TypeDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(ExportedTypeHandle.FromRowId(1).IsNil);
            Assert.False(TypeReferenceHandle.FromRowId(1).IsNil);
            Assert.False(TypeSpecificationHandle.FromRowId(1).IsNil);
            Assert.False(MemberReferenceHandle.FromRowId(1).IsNil);
            Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(EventDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(StandaloneSignatureHandle.FromRowId(1).IsNil);
            Assert.False(MemberReferenceHandle.FromRowId(1).IsNil);
            Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(EventDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil);
            Assert.False(ParameterHandle.FromRowId(1).IsNil);
            Assert.False(GenericParameterHandle.FromRowId(1).IsNil);
            Assert.False(GenericParameterConstraintHandle.FromRowId(1).IsNil);
            Assert.False(ModuleReferenceHandle.FromRowId(1).IsNil);
            Assert.False(CustomAttributeHandle.FromRowId(1).IsNil);
            Assert.False(DeclarativeSecurityAttributeHandle.FromRowId(1).IsNil);
            Assert.False(ManifestResourceHandle.FromRowId(1).IsNil);
            Assert.False(ConstantHandle.FromRowId(1).IsNil);
            Assert.False(ManifestResourceHandle.FromRowId(1).IsNil);
            Assert.False(AssemblyFileHandle.FromRowId(1).IsNil);
            Assert.False(MethodImplementationHandle.FromRowId(1).IsNil);
            Assert.False(AssemblyReferenceHandle.FromRowId(1).IsNil);

            Assert.False(((EntityHandle)ModuleDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)AssemblyDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)InterfaceImplementationHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)MethodDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)MethodSpecificationHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)TypeDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)ExportedTypeHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)TypeReferenceHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)TypeSpecificationHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)StandaloneSignatureHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)ParameterHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)GenericParameterHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)GenericParameterConstraintHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)ModuleReferenceHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)CustomAttributeHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)ConstantHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)AssemblyFileHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)MethodImplementationHandle.FromRowId(1)).IsNil);
            Assert.False(((EntityHandle)AssemblyReferenceHandle.FromRowId(1)).IsNil);

            Assert.False(StringHandle.FromOffset(1).IsNil);
            Assert.False(BlobHandle.FromOffset(1).IsNil);
            Assert.False(UserStringHandle.FromOffset(1).IsNil);
            Assert.False(GuidHandle.FromIndex(1).IsNil);

            Assert.False(((Handle)StringHandle.FromOffset(1)).IsNil);
            Assert.False(((Handle)BlobHandle.FromOffset(1)).IsNil);
            Assert.False(((Handle)UserStringHandle.FromOffset(1)).IsNil);
            Assert.False(((Handle)GuidHandle.FromIndex(1)).IsNil);

            Assert.True(ModuleDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(AssemblyDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(InterfaceImplementationHandle.FromRowId(0).IsNil);
            Assert.True(MethodDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(MethodSpecificationHandle.FromRowId(0).IsNil);
            Assert.True(TypeDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(ExportedTypeHandle.FromRowId(0).IsNil);
            Assert.True(TypeReferenceHandle.FromRowId(0).IsNil);
            Assert.True(TypeSpecificationHandle.FromRowId(0).IsNil);
            Assert.True(MemberReferenceHandle.FromRowId(0).IsNil);
            Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(EventDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(StandaloneSignatureHandle.FromRowId(0).IsNil);
            Assert.True(MemberReferenceHandle.FromRowId(0).IsNil);
            Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(EventDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil);
            Assert.True(ParameterHandle.FromRowId(0).IsNil);
            Assert.True(GenericParameterHandle.FromRowId(0).IsNil);
            Assert.True(GenericParameterConstraintHandle.FromRowId(0).IsNil);
            Assert.True(ModuleReferenceHandle.FromRowId(0).IsNil);
            Assert.True(CustomAttributeHandle.FromRowId(0).IsNil);
            Assert.True(DeclarativeSecurityAttributeHandle.FromRowId(0).IsNil);
            Assert.True(ManifestResourceHandle.FromRowId(0).IsNil);
            Assert.True(ConstantHandle.FromRowId(0).IsNil);
            Assert.True(ManifestResourceHandle.FromRowId(0).IsNil);
            Assert.True(AssemblyFileHandle.FromRowId(0).IsNil);
            Assert.True(MethodImplementationHandle.FromRowId(0).IsNil);
            Assert.True(AssemblyReferenceHandle.FromRowId(0).IsNil);

            Assert.True(((EntityHandle)ModuleDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)AssemblyDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)InterfaceImplementationHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)MethodDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)MethodSpecificationHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)TypeDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)ExportedTypeHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)TypeReferenceHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)TypeSpecificationHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)StandaloneSignatureHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)ParameterHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)GenericParameterHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)GenericParameterConstraintHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)ModuleReferenceHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)CustomAttributeHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)ConstantHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)AssemblyFileHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)MethodImplementationHandle.FromRowId(0)).IsNil);
            Assert.True(((EntityHandle)AssemblyReferenceHandle.FromRowId(0)).IsNil);

            // heaps:
            Assert.True(StringHandle.FromOffset(0).IsNil);
            Assert.True(BlobHandle.FromOffset(0).IsNil);
            Assert.True(UserStringHandle.FromOffset(0).IsNil);
            Assert.True(GuidHandle.FromIndex(0).IsNil);

            Assert.True(((Handle)StringHandle.FromOffset(0)).IsNil);
            Assert.True(((Handle)BlobHandle.FromOffset(0)).IsNil);
            Assert.True(((Handle)UserStringHandle.FromOffset(0)).IsNil);
            Assert.True(((Handle)GuidHandle.FromIndex(0)).IsNil);

            // virtual:
            Assert.False(AssemblyReferenceHandle.FromVirtualIndex(0).IsNil);
            Assert.False(StringHandle.FromVirtualIndex(0).IsNil);
            Assert.False(BlobHandle.FromVirtualIndex(0, 0).IsNil);

            Assert.False(((Handle)AssemblyReferenceHandle.FromVirtualIndex(0)).IsNil);
            Assert.False(((Handle)StringHandle.FromVirtualIndex(0)).IsNil);
            Assert.False(((Handle)BlobHandle.FromVirtualIndex(0, 0)).IsNil);
        }
 public void AddMethodSpecification(EntityHandle method, BlobHandle instantiation)
 {
     _methodSpecTable.Add(new MethodSpecRow
     {
         Method = (uint)CodedIndex.ToMethodDefOrRef(method),
         Instantiation = instantiation
     });
 }
Exemple #59
0
        private long GetData(ColumnData column, BlobHandle blob, int length, object buffer, int bufferOffset)
        {
            Debug.WriteLineIf(CLI.FnTrace.Enabled, "ManagedCommand.GetData()");

            Future future = new Future(Service.GetData,
                                       blob.current_page,
                                       length,
                                       blob.current_position,
                                       blob.keyId,
                                       blob.fragNo,
                                       blob.dirPage,
                                       blob.pages,
                                       blob.tag == BoxTag.DV_BLOB_WIDE_HANDLE ? 1 : 0,
                                       blob.timeStamp);

            object result = null;

            try
            {
                connection.futures.Add(future);
                future.SendRequest(connection.Session, timeout);
                result = future.GetResult(connection.Session, connection.futures);
            }
            finally
            {
                connection.futures.Remove(future);
            }

            if (!(result is object[]))
            {
                return(0);
            }

            object[] results = (object[])result;
            if (results[0] is int && (AnswerTag)results[0] == AnswerTag.QA_ERROR)
            {
                errors.AddServerError((string)results[1], null, (string)results[2]);
                Diagnostics.HandleResult(CLI.ReturnCode.SQL_ERROR, this, connection.OuterConnection);
            }

            int startOffset = column.lobOffset;

            for (int i = 0; i < results.Length; i++)
            {
                if (results[i] is int[])
                {
                    int[] array = (int[])results[i];
                    blob.current_page     = array[1];
                    blob.current_position = array[2];
                    continue;
                }
                else if (results[i] is string)
                {
                    string s = (string)results[i];
                    if (buffer is char[])
                    {
                        char[] chars      = s.ToCharArray();
                        char[] charBuffer = (char[])buffer;

                        Debug.WriteLineIf(Switch.Enabled, "do chars");
                        Debug.WriteLineIf(Switch.Enabled, "buffer length: " +
                                          (charBuffer == null ? "no" : charBuffer.Length.ToString()));
                        Debug.WriteLineIf(Switch.Enabled, "buffer offset: " + bufferOffset);
                        Debug.WriteLineIf(Switch.Enabled, "data length: " + chars.Length);
                        Debug.WriteLineIf(Switch.Enabled, "length: " + length);

                        if (charBuffer != null)
                        {
                            int copyLength = length < chars.Length ? length : chars.Length;
                            Array.Copy(chars, 0, charBuffer, bufferOffset, copyLength);
                        }
                        column.lobOffset += chars.Length;
                        bufferOffset     += chars.Length;
                        length           -= chars.Length;
                    }
                    else
                    {
                        byte[] bytes      = Encoding.GetEncoding("iso-8859-1").GetBytes(s);
                        byte[] byteBuffer = (byte[])buffer;

                        Debug.WriteLineIf(Switch.Enabled, "do bytes");
                        Debug.WriteLineIf(Switch.Enabled, "buffer length: " +
                                          (byteBuffer == null ? "no" : byteBuffer.Length.ToString()));
                        Debug.WriteLineIf(Switch.Enabled, "buffer offset: " + bufferOffset);
                        Debug.WriteLineIf(Switch.Enabled, "data length: " + bytes.Length);
                        Debug.WriteLineIf(Switch.Enabled, "length: " + length);

                        if (byteBuffer != null)
                        {
                            int copyLength = length < bytes.Length ? length : bytes.Length;
                            Array.Copy(bytes, 0, byteBuffer, bufferOffset, copyLength);
                        }
                        column.lobOffset += bytes.Length;
                        bufferOffset     += bytes.Length;
                        length           -= bytes.Length;
                    }
                }
            }
            return(column.lobOffset - startOffset);
        }
 public void AddFieldDefinition(
     FieldAttributes attributes,
     StringHandle name,
     BlobHandle signature)
 {
     _fieldTable.Add(new FieldDefRow
     {
         Flags = (ushort)attributes,
         Name = name,
         Signature = signature
     });
 }