// Virtual function related functionality public override MethodImplRecord[] FindMethodsImplWithMatchingDeclName(string declName) { MetadataReader metadataReader = _module.MetadataReader; var stringComparer = metadataReader.StringComparer; ArrayBuilder<MethodImplRecord> foundRecords = new ArrayBuilder<MethodImplRecord>(); foreach (var methodImplHandle in _typeDefinition.GetMethodImplementations()) { MethodImplementation methodImpl = metadataReader.GetMethodImplementation(methodImplHandle); EntityHandle methodDeclCheckHandle = methodImpl.MethodDeclaration; HandleKind methodDeclHandleKind = methodDeclCheckHandle.Kind; // We want to check that the method name matches before actually getting the MethodDesc. For MethodSpecifications // we need to dereference that handle to the underlying member reference to look at name matching. if (methodDeclHandleKind == HandleKind.MethodSpecification) { methodDeclCheckHandle = metadataReader.GetMethodSpecification((MethodSpecificationHandle)methodDeclCheckHandle).Method; methodDeclHandleKind = methodDeclCheckHandle.Kind; } bool foundRecord = false; switch (methodDeclHandleKind) { case HandleKind.MethodDefinition: if (stringComparer.Equals(metadataReader.GetMethodDefinition((MethodDefinitionHandle)methodDeclCheckHandle).Name, declName)) { foundRecord = true; } break; case HandleKind.MemberReference: if (stringComparer.Equals(metadataReader.GetMemberReference((MemberReferenceHandle)methodDeclCheckHandle).Name, declName)) { foundRecord = true; } break; default: Debug.Assert(false, "unexpected methodDeclHandleKind"); break; } if (foundRecord) { MethodImplRecord newRecord = new MethodImplRecord(); newRecord.Decl = (MethodDesc)_module.GetObject(methodImpl.MethodDeclaration); newRecord.Body = (MethodDesc)_module.GetObject(methodImpl.MethodBody); foundRecords.Add(newRecord); } } if (foundRecords.Count != 0) return foundRecords.ToArray(); return null; }
public void ParameterlessConstructor() { var builder = new ArrayBuilder <T>(); // Should default to count/capacity of 0 Assert.Equal(0, builder.Count); Assert.Equal(0, builder.Capacity); // Should use a cached array for capacity of 0 Assert.Same(Array.Empty <T>(), builder.ToArray()); }
public virtual ICollection <NativeLayoutVertexNode> GetTemplateEntries(NodeFactory factory) { ArrayBuilder <NativeLayoutVertexNode> templateEntries = new ArrayBuilder <NativeLayoutVertexNode>(); foreach (var entry in Entries) { templateEntries.Add(entry.TemplateDictionaryNode(factory)); } return(templateEntries.ToArray()); }
public void ToArray(IEnumerable <T> seed) { ArrayBuilder <T> builder = CreateBuilderFromSequence(seed); int count = builder.Count; // Count needs to be called beforehand. T[] array = builder.ToArray(); // ToArray should only be called once. Assert.Equal(count, array.Length); Assert.Equal(seed, array); }
public NsScriptProcessDump Dump() { Debug.Assert(PendingThreadActions.Count == 0); return(new NsScriptProcessDump { Id = Id, ClockBaseMs = Ticks / (double)Stopwatch.Frequency * 1000.0d, MainThread = MainThread.Id, Threads = _threads.ToArray().Select(x => x.Dump()).ToArray() }); }
public void IEnumerable___correct_result() { int[] expected = Getvalues().ToArray(); var sut = new ArrayBuilder <int>(true); sut.AddRange(Getvalues()); int[] actual = sut.ToArray(); CollectionAssert.AreEqual(expected, actual); }
public PrecomputedDictionaryLayoutNode(TypeSystemEntity owningMethodOrType, IEnumerable <GenericLookupResult> layout) : base(owningMethodOrType) { ArrayBuilder <GenericLookupResult> l = new ArrayBuilder <GenericLookupResult>(); foreach (var entry in layout) { l.Add(entry); } _layout = l.ToArray(); }
private Object ResolveMethodInstantiation(MethodInstantiationHandle handle) { MethodInstantiation methodInstantiation = _metadataReader.GetMethodInstantiation(handle); MethodDesc genericMethodDef = (MethodDesc)GetObject(methodInstantiation.Method, null); ArrayBuilder <TypeDesc> instantiation = new ArrayBuilder <TypeDesc>(); foreach (Handle genericArgHandle in methodInstantiation.GenericTypeArguments) { instantiation.Add(GetType(genericArgHandle)); } return(Context.GetInstantiatedMethod(genericMethodDef, new Instantiation(instantiation.ToArray()))); }
CustomAttribute[] ProcessAttributes(XPathNavigator nav, ICustomAttributeProvider provider) { XPathNodeIterator iterator = nav.SelectChildren("attribute", string.Empty); var builder = new ArrayBuilder <CustomAttribute> (); while (iterator.MoveNext()) { if (!ShouldProcessElement(iterator.Current)) { continue; } TypeDefinition attributeType; string internalAttribute = GetAttribute(iterator.Current, "internal"); if (!string.IsNullOrEmpty(internalAttribute)) { attributeType = GenerateRemoveAttributeInstancesAttribute(); if (attributeType == null) { continue; } // TODO: Replace with IsAttributeType check once we have it if (provider is not TypeDefinition) { _context.LogWarning($"Internal attribute '{attributeType.Name}' can only be used on attribute types", 2048, _xmlDocumentLocation); continue; } } else { string attributeFullName = GetFullName(iterator.Current); if (string.IsNullOrEmpty(attributeFullName)) { _context.LogWarning($"'attribute' element does not contain attribute 'fullname' or it's empty", 2029, _xmlDocumentLocation); continue; } if (!GetAttributeType(iterator, attributeFullName, out attributeType)) { continue; } } CustomAttribute customAttribute = CreateCustomAttribute(iterator, attributeType); if (customAttribute != null) { _context.LogMessage($"Assigning external custom attribute '{FormatCustomAttribute (customAttribute)}' instance to '{provider}'"); builder.Add(customAttribute); } } return(builder.ToArray());
// Virtual function related functionality public override MethodImplRecord[] FindMethodsImplWithMatchingDeclName(string declName) { MetadataReader metadataReader = _metadataUnit.MetadataReader; ArrayBuilder <MethodImplRecord> foundRecords = new ArrayBuilder <MethodImplRecord>(); foreach (var methodImplHandle in _typeDefinition.MethodImpls) { MethodImpl methodImpl = metadataReader.GetMethodImpl(methodImplHandle); Handle methodDeclCheckHandle = methodImpl.MethodDeclaration; HandleType methodDeclHandleType = methodDeclCheckHandle.HandleType; bool foundRecord = false; switch (methodDeclHandleType) { case HandleType.QualifiedMethod: QualifiedMethod qualifiedMethod = metadataReader.GetQualifiedMethod(methodDeclCheckHandle.ToQualifiedMethodHandle(metadataReader)); Method method = qualifiedMethod.Method.GetMethod(metadataReader); if (method.Name.StringEquals(declName, metadataReader)) { foundRecord = true; } break; case HandleType.MemberReference: { MemberReference memberRef = metadataReader.GetMemberReference(methodDeclCheckHandle.ToMemberReferenceHandle(metadataReader)); if (memberRef.Name.StringEquals(declName, metadataReader)) { foundRecord = true; } } break; } if (foundRecord) { MethodDesc newRecordDecl = (MethodDesc)_metadataUnit.GetObject(methodImpl.MethodDeclaration, null); MethodDesc newRecordBody = (MethodDesc)_metadataUnit.GetObject(methodImpl.MethodBody, null); foundRecords.Add(new MethodImplRecord(newRecordDecl, newRecordBody)); } } if (foundRecords.Count != 0) { return(foundRecords.ToArray()); } return(null); }
private void btnCrArr_Click(object sender, EventArgs e) { // With the v4.5 feature, you can directly put the size of the array that you want, instead of to allocate a buffer yourself, the ctor do it for you. ArrayBuilder Build = new ArrayBuilder(0x50); Build.Write.SetBool(3, true); Build.Write.SetFloat(4, 1000); Build.Write.SetInt32(8, 1337); Build.Write.SetString(20, "iMCSx ArrayBuilder !"); PS3.SetMemory(0x10060000, Build.ToArray()); MessageBox.Show("Done, try to read now !"); }
internal static Expansion CreateExpansion(ArrayBuilder<Expansion> expansions) { switch (expansions.Count) { case 0: return null; case 1: return expansions[0]; default: return new AggregateExpansion(expansions.ToArray()); } }
public void Add_item_then_AddRange_with_array___correct_result() { int[] expected = new int[] { 42 }.Concat(Getvalues()).ToArray(); var sut = new ArrayBuilder <int>(true); sut.Add(42); sut.AddRange(Getvalues().ToArray()); int[] actual = sut.ToArray(); CollectionAssert.AreEqual(expected, actual); }
public void CapacityConstructor(int capacity) { Debug.Assert(capacity >= 0); var builder = new ArrayBuilder <T>(capacity); Assert.Equal(0, builder.Count); Assert.Equal(capacity, builder.Capacity); // Should use a cached array for count of 0, regardless of capacity Assert.Same(Array.Empty <T>(), builder.ToArray()); }
public override ICompilation ToCompilation() { ArrayBuilder <CorJitFlag> jitFlagBuilder = new ArrayBuilder <CorJitFlag>(); switch (_optimizationMode) { case OptimizationMode.None: jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_DEBUG_CODE); break; case OptimizationMode.PreferSize: jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_SIZE_OPT); break; case OptimizationMode.PreferSpeed: jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_SPEED_OPT); break; default: // Not setting a flag results in BLENDED_CODE. break; } if (_optimizationMode != OptimizationMode.None && _profileDataManager != null) { jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_BBOPT); } // Do not bother with debug information if the debug info provider never gives anything. if (!(_debugInformationProvider is NullDebugInformationProvider)) { jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_DEBUG_INFO); } RyuJitCompilationOptions options = 0; if (_methodBodyFolding) { options |= RyuJitCompilationOptions.MethodBodyFolding; } if ((_mitigationOptions & SecurityMitigationOptions.ControlFlowGuardAnnotations) != 0) { options |= RyuJitCompilationOptions.ControlFlowGuardAnnotations; } var factory = new RyuJitNodeFactory(_context, _compilationGroup, _metadataManager, _interopStubManager, _nameMangler, _vtableSliceProvider, _dictionaryLayoutProvider, GetPreinitializationManager()); JitConfigProvider.Initialize(_context.Target, jitFlagBuilder.ToArray(), _ryujitOptions); DependencyAnalyzerBase <NodeFactory> graph = CreateDependencyGraph(factory, new ObjectNode.ObjectNodeComparer(new CompilerComparer())); return(new RyuJitCompilation(graph, factory, _compilationRoots, _ilProvider, _debugInformationProvider, _logger, _devirtualizationManager, _inliningPolicy ?? _compilationGroup, _instructionSetSupport, _profileDataManager, _methodImportationErrorProvider, options, _parallelism)); }
CustomAttribute[]? ProcessAttributes(XPathNavigator nav, ICustomAttributeProvider provider) { var builder = new ArrayBuilder <CustomAttribute>(); foreach (XPathNavigator argumentNav in nav.SelectChildren("attribute", string.Empty)) { if (!ShouldProcessElement(argumentNav)) { continue; } TypeDefinition?attributeType; string internalAttribute = GetAttribute(argumentNav, "internal"); if (!string.IsNullOrEmpty(internalAttribute)) { attributeType = GenerateRemoveAttributeInstancesAttribute(); if (attributeType == null) { continue; } // TODO: Replace with IsAttributeType check once we have it if (provider is not TypeDefinition) { LogWarning(argumentNav, DiagnosticId.XmlRemoveAttributeInstancesCanOnlyBeUsedOnType, attributeType.Name); continue; } } else { string attributeFullName = GetFullName(argumentNav); if (string.IsNullOrEmpty(attributeFullName)) { LogWarning(argumentNav, DiagnosticId.XmlElementDoesNotContainRequiredAttributeFullname); continue; } if (!GetAttributeType(argumentNav, attributeFullName, out attributeType)) { continue; } } CustomAttribute?customAttribute = CreateCustomAttribute(argumentNav, attributeType); if (customAttribute != null) { _context.LogMessage($"Assigning external custom attribute '{FormatCustomAttribute(customAttribute)}' instance to '{provider}'."); builder.Add(customAttribute); } } return(builder.ToArray());
public ObjectNode.ObjectData ToObjectData() { #if DEBUG Debug.Assert(_numReservations == 0); #endif ObjectNode.ObjectData returnData = new ObjectNode.ObjectData(_data.ToArray(), _relocs.ToArray(), Alignment, DefinedSymbols.ToArray()); return(returnData); }
public void Works() { // Arrange byte[] testArray; using (ArrayBuilder <byte> con = new ArrayBuilder <byte>()) { con.AppendToArray(BitConverter.GetBytes((uint)1)); con.AppendToArray(BitConverter.GetBytes(1)); con.AppendToArray(BitConverter.GetBytes(true)); con.AppendToArray(BitConverter.GetBytes('a')); con.AppendToArray(BitConverter.GetBytes(1.1f)); con.AppendToArray(BitConverter.GetBytes(1.1d)); con.AppendToArray(Encoding.UTF8.GetBytes("aaa")); con.AppendToArray(Encoding.UTF32.GetBytes("aaa")); con.AppendToArray(new byte[] { 1, 1, 1 }); testArray = con.ToArray(); } // Act using (ByteArrayExtractor ex = new ByteArrayExtractor(testArray)) { uint test1 = ex.ExtractUInt(); int test2 = ex.ExtractInt(); bool test3 = ex.ExtractBool(); char test4 = ex.ExtractChar(); float test5 = ex.ExtractFloat(); double test6 = ex.ExtractDouble(); string test7s1 = ex.ExtractString(3, Encoding.UTF8); string test7s2 = ex.ExtractString(3, Encoding.UTF32); byte[] test8 = ex.ExtractRemaining(); // Assert Assert.That(test1 == 1); Assert.That(test2 == 1); Assert.That(test3 == true); Assert.That(test4 == 'a'); Assert.That(test5 == 1.1f); Assert.That(test6 == 1.1); Assert.That(test7s1 == "aaa"); Assert.That(test7s2 == "aaa"); Assert.That(test8.Length == 3); foreach (byte b in test8) { Assert.That(b == 1); } } }
public override ICompilation ToCompilation() { ArrayBuilder <CorJitFlag> jitFlagBuilder = new ArrayBuilder <CorJitFlag>(); switch (_optimizationMode) { case OptimizationMode.None: jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_DEBUG_CODE); break; case OptimizationMode.PreferSize: jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_SIZE_OPT); break; case OptimizationMode.PreferSpeed: jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_SPEED_OPT); break; default: // Not setting a flag results in BLENDED_CODE. break; } // Do not bother with debug information if the debug info provider never gives anything. if (!(_debugInformationProvider is NullDebugInformationProvider)) { jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_DEBUG_INFO); } if (_context.Target.MaximumSimdVectorLength != SimdVectorLength.None) { // TODO: AVX Debug.Assert(_context.Target.MaximumSimdVectorLength == SimdVectorLength.Vector128Bit); jitFlagBuilder.Add(CorJitFlag.CORJIT_FLAG_FEATURE_SIMD); } RyuJitCompilationOptions options = 0; if (_methodBodyFolding) { options |= RyuJitCompilationOptions.MethodBodyFolding; } var interopStubManager = new CompilerGeneratedInteropStubManager(_compilationGroup, _context, new InteropStateManager(_context.GeneratedAssembly)); var factory = new RyuJitNodeFactory(_context, _compilationGroup, _metadataManager, interopStubManager, _nameMangler, _vtableSliceProvider, _dictionaryLayoutProvider); var jitConfig = new JitConfigProvider(jitFlagBuilder.ToArray(), _ryujitOptions); DependencyAnalyzerBase <NodeFactory> graph = CreateDependencyGraph(factory, new ObjectNode.ObjectNodeComparer(new CompilerComparer())); return(new RyuJitCompilation(graph, factory, _compilationRoots, _ilProvider, _debugInformationProvider, _pinvokePolicy, _logger, _devirtualizationManager, jitConfig, options)); }
protected override MethodImplRecord[] ComputeVirtualMethodImplsForType() { ArrayBuilder <MethodImplRecord> records = new ArrayBuilder <MethodImplRecord>(); MetadataReader metadataReader = _module.MetadataReader; foreach (var methodImplHandle in _typeDefinition.GetMethodImplementations()) { MethodImplementation methodImpl = metadataReader.GetMethodImplementation(methodImplHandle); EntityHandle methodDeclCheckHandle = methodImpl.MethodDeclaration; HandleKind methodDeclHandleKind = methodDeclCheckHandle.Kind; // We want to check that the type is not an interface matches before actually getting the MethodDesc. // For MethodSpecifications we need to dereference that handle to the underlying member reference to // look at the owning type. if (methodDeclHandleKind == HandleKind.MethodSpecification) { methodDeclCheckHandle = metadataReader.GetMethodSpecification((MethodSpecificationHandle)methodDeclCheckHandle).Method; methodDeclHandleKind = methodDeclCheckHandle.Kind; } MetadataType owningType = null; switch (methodDeclHandleKind) { case HandleKind.MethodDefinition: owningType = ((MethodDesc)_module.GetObject(methodDeclCheckHandle)).OwningType as MetadataType; break; case HandleKind.MemberReference: EntityHandle owningTypeHandle = metadataReader.GetMemberReference((MemberReferenceHandle)methodDeclCheckHandle).Parent; owningType = _module.GetObject(owningTypeHandle) as MetadataType; break; default: Debug.Fail("unexpected methodDeclHandleKind"); break; } if (!owningType.IsInterface) { MethodImplRecord newRecord = new MethodImplRecord( (MethodDesc)_module.GetObject(methodImpl.MethodDeclaration), (MethodDesc)_module.GetObject(methodImpl.MethodBody)); records.Add(newRecord); } } return(records.ToArray()); }
public static Byte[] ReadAllBytes(this Stream stream, Int32 bufferSize = DefaultBufferSize) { var result = new ArrayBuilder <Byte>(); var buffer = new Byte[bufferSize]; Int32 len; while (0 < (len = stream.Read(buffer, 0, bufferSize))) { result.Append(buffer, 0, len); } return(result.ToArray()); }
protected override Tuple <TypeDesc, MethodDesc[]> CreateValueFromKey(TypeDesc key) { ArrayBuilder <MethodDesc> virtualMethods = new ArrayBuilder <MethodDesc>(); foreach (var method in key.GetMethods()) { if (method.IsVirtual) { virtualMethods.Add(method); } } return(new Tuple <TypeDesc, MethodDesc[]>(key, virtualMethods.ToArray())); }
internal static Expansion CreateExpansion(ArrayBuilder <Expansion> expansions) { switch (expansions.Count) { case 0: return(null); case 1: return(expansions[0]); default: return(new AggregateExpansion(expansions.ToArray())); } }
public EagerlyBuiltVTableSliceNode(TypeDesc type) : base(type) { var slots = new ArrayBuilder <MethodDesc>(); MetadataType mdType = _type.GetClosestMetadataType(); foreach (var method in mdType.GetAllVirtualMethods()) { slots.Add(method); } _slots = slots.ToArray(); }
public void Add_items_ToArray___correct_result(int size) { var expected = new int[size]; var sut = new ArrayBuilder <int>(true); for (int i = 0; i < size; ++i) { expected[i] = i; sut.Add(i); } int[] actual = sut.ToArray(); CollectionAssert.AreEqual(expected, actual); }
public static ObjectDumper Compose(IEnumerable <ObjectDumper> dumpers) { var dumpersList = new ArrayBuilder <ObjectDumper>(); foreach (var dumper in dumpers) { dumpersList.Add(dumper); } return(dumpersList.Count switch { 0 => null, 1 => dumpersList[0], _ => new ComposedObjectDumper(dumpersList.ToArray()), });
public virtual ICollection <NativeLayoutVertexNode> GetTemplateEntries(NodeFactory factory) { if (_layout == null) { ComputeLayout(); } ArrayBuilder <NativeLayoutVertexNode> templateEntries = new ArrayBuilder <NativeLayoutVertexNode>(); for (int i = 0; i < _layout.Length; i++) { templateEntries.Add(_layout[i].TemplateDictionaryNode(factory)); } return(templateEntries.ToArray()); }
public void Add_item_up_to_StartingCapacity_then_AddRange_with_array_then_add_another_item___correct_result() { int[] expected = new int[] { 42, 41, 40, 39 }.Concat(Getvalues()).Concat(new[] { 3 }).ToArray(); var sut = new ArrayBuilder <int>(true); sut.Add(42); sut.Add(41); sut.Add(40); sut.Add(39); sut.AddRange(Getvalues().ToArray()); sut.Add(3); int[] actual = sut.ToArray(); CollectionAssert.AreEqual(expected, actual); }
public override Byte[] Read(JsonReader reader, Type objectType) { reader.ReadStartArray(); Span <Byte> buffer = stackalloc Byte[128]; var builder = new ArrayBuilder(buffer); while (reader.Peek() != JsonToken.EndArray) { builder.Add(reader.ReadByte()); } reader.ReadEndArray(); return(builder.ToArray()); }
/// <summary> /// Creates a new instance of <see cref="JitConfigProvider"/>. /// </summary> /// <param name="jitFlags">A collection of JIT compiler flags.</param> /// <param name="parameters">A collection of parameter name/value pairs.</param> /// <param name="jitPath">A path to the JIT library to be used (may be null).</param> public JitConfigProvider(IEnumerable <CorJitFlag> jitFlags, IEnumerable <KeyValuePair <string, string> > parameters) { ArrayBuilder <CorJitFlag> jitFlagBuilder = new ArrayBuilder <CorJitFlag>(); foreach (CorJitFlag jitFlag in jitFlags) { jitFlagBuilder.Add(jitFlag); } _jitFlags = jitFlagBuilder.ToArray(); foreach (var param in parameters) { _config[param.Key] = param.Value; } UnmanagedInstance = CreateUnmanagedInstance(); }
void ProcessMethodChildren(TypeDefinition type, MethodDefinition method, XPathNodeIterator iterator) { ArrayBuilder <Attribute> attributes = ProcessAttributes(iterator); ArrayBuilder <(string, ArrayBuilder <Attribute>)> parameterAnnotations = ProcessParameters(type, method, iterator.Current.SelectChildren("parameter", string.Empty)); ArrayBuilder <ArrayBuilder <Attribute> > returnParameterAnnotations = ProcessReturnParameters(type, method, iterator.Current.SelectChildren("return", string.Empty)); var parameterAnnotation = new ArrayBuilder <(string ParamName, DynamicallyAccessedMemberTypes Annotation)> (); DynamicallyAccessedMemberTypes returnAnnotation = 0; if (parameterAnnotations.Count > 0) { foreach (var parameter in parameterAnnotations.ToArray()) { DynamicallyAccessedMemberTypes paramAnnotation = GetMemberTypesForDynamicallyAccessedMemberAttribute(parameter.Item2, _context, _xmlDocumentLocation); if (paramAnnotation != 0) { parameterAnnotation.Add((parameter.Item1, paramAnnotation)); } } } if (returnParameterAnnotations.Count == 1) { foreach (var returnparameter in returnParameterAnnotations.ToArray()) { DynamicallyAccessedMemberTypes returnparamAnnotation = GetMemberTypesForDynamicallyAccessedMemberAttribute(returnparameter, _context, _xmlDocumentLocation); if (returnparamAnnotation != 0) { returnAnnotation = returnparamAnnotation; } } } else { _context.LogMessage(MessageContainer.CreateWarningMessage(_context, $"There is more than one return parameter specified for '{method.Name}' in '{_xmlDocumentLocation}'", 2023, _xmlDocumentLocation)); } if (returnAnnotation != 0 || parameterAnnotation.Count > 0) { _methods[method] = new AnnotatedMethod(returnAnnotation, parameterAnnotation.ToArray()); } }
protected override MethodImplRecord[] ComputeVirtualMethodImplsForType() { ArrayBuilder <MethodImplRecord> records = new ArrayBuilder <MethodImplRecord>(); MetadataReader metadataReader = _metadataUnit.MetadataReader; foreach (var methodImplHandle in _typeDefinition.MethodImpls) { MethodImpl methodImpl = metadataReader.GetMethodImpl(methodImplHandle); Handle methodDeclCheckHandle = methodImpl.MethodDeclaration; HandleType methodDeclHandleType = methodDeclCheckHandle.HandleType; MetadataType owningType = null; switch (methodDeclHandleType) { case HandleType.QualifiedMethod: QualifiedMethod qualifiedMethod = metadataReader.GetQualifiedMethod(methodDeclCheckHandle.ToQualifiedMethodHandle(metadataReader)); owningType = (MetadataType)_metadataUnit.GetType(qualifiedMethod.EnclosingType); break; case HandleType.MemberReference: Handle owningTypeHandle = metadataReader.GetMemberReference(methodDeclCheckHandle.ToMemberReferenceHandle(metadataReader)).Parent; owningType = _metadataUnit.GetType(owningTypeHandle) as MetadataType; break; default: Debug.Assert(false, "unexpected methodDeclHandleType"); break; } // We want to check that the type is not an interface match before actually getting the MethodDesc. if (!owningType.IsInterface) { MethodDesc newRecordDecl = (MethodDesc)_metadataUnit.GetObject(methodImpl.MethodDeclaration, null); MethodDesc newRecordBody = (MethodDesc)_metadataUnit.GetObject(methodImpl.MethodBody, null); records.Add(new MethodImplRecord(newRecordDecl, newRecordBody)); } } return(records.ToArray()); }
/// <summary> /// Metadata based computation of interfaces. /// </summary> private DefType[] ComputeRuntimeInterfacesForNonInstantiatedMetadataType(MetadataType type) { DefType[] explicitInterfaces = type.ExplicitlyImplementedInterfaces; DefType[] baseTypeInterfaces = (type.BaseType != null) ? (type.BaseType.RuntimeInterfaces) : Array.Empty<DefType>(); // Optimized case for no interfaces newly defined. if (explicitInterfaces.Length == 0) return baseTypeInterfaces; ArrayBuilder<DefType> interfacesArray = new ArrayBuilder<DefType>(); interfacesArray.Append(baseTypeInterfaces); foreach (DefType iface in explicitInterfaces) { BuildPostOrderInterfaceList(iface, ref interfacesArray); } return interfacesArray.ToArray(); }
public void AddRange() { var builder = new ArrayBuilder<int>(); builder.AddRange(new int[0], 0, 0); AssertEx.Equal(new int[0], builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 0, 3); AssertEx.Equal(new[] { 1, 2, 3 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 2, 0); AssertEx.Equal(new[] { 1, 2, 3 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 1, 1); AssertEx.Equal(new[] { 1, 2, 3, 2 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 1, 2); AssertEx.Equal(new[] { 1, 2, 3, 2, 2, 3 }, builder.ToArray()); builder.AddRange(new[] { 1, 2, 3 }, 2, 1); AssertEx.Equal(new[] { 1, 2, 3, 2, 2, 3, 3 }, builder.ToArray()); }
private void SetDebugInformation(MethodCodeNode methodCodeNodeNeedingCode, MethodIL methodIL) { try { MethodDebugInformation debugInfo = _compilation.GetDebugInfo(methodIL); // TODO: NoLineNumbers //if (!_compilation.Options.NoLineNumbers) { IEnumerable<ILSequencePoint> ilSequencePoints = debugInfo.GetSequencePoints(); if (ilSequencePoints != null) { SetSequencePoints(ilSequencePoints); } } IEnumerable<ILLocalVariable> localVariables = debugInfo.GetLocalVariables(); if (localVariables != null) { SetLocalVariables(localVariables); } IEnumerable<string> parameters = debugInfo.GetParameterNames(); if (parameters != null) { SetParameterNames(parameters); } ArrayBuilder<uint> variableToTypeIndex = new ArrayBuilder<uint>(); var signature = MethodBeingCompiled.Signature; if (!signature.IsStatic) { TypeDesc type = MethodBeingCompiled.OwningType; variableToTypeIndex.Add(GetVariableTypeIndex(type)); } for (int i = 0; i < signature.Length; ++i) { TypeDesc type = signature[i]; variableToTypeIndex.Add(GetVariableTypeIndex(type)); } var locals = methodIL.GetLocals(); for (int i = 0; i < locals.Length; ++i) { TypeDesc type = locals[i].Type; variableToTypeIndex.Add(GetVariableTypeIndex(type)); } _variableToTypeIndex = variableToTypeIndex.ToArray(); } catch (Exception e) { // Debug info not successfully loaded. Log.WriteLine(e.Message + " (" + methodCodeNodeNeedingCode.ToString() + ")"); } }
DispatchMapEntry[] BuildDispatchMap(NodeFactory factory) { ArrayBuilder<DispatchMapEntry> dispatchMapEntries = new ArrayBuilder<DispatchMapEntry>(); for (int i = 0; i < _type.RuntimeInterfaces.Length; i++) { var interfaceType = _type.RuntimeInterfaces[i]; Debug.Assert(interfaceType.IsInterface); List<MethodDesc> virtualSlots; factory.VirtualSlots.TryGetValue(interfaceType, out virtualSlots); if (virtualSlots != null) { for (int j = 0; j < virtualSlots.Count; j++) { MethodDesc declMethod = virtualSlots[j]; var implMethod = VirtualFunctionResolution.ResolveInterfaceMethodToVirtualMethodOnType(declMethod, _type.GetClosestMetadataType()); // Interface methods first implemented by a base type in the hierarchy will return null for the implMethod (runtime interface // dispatch will walk the inheritance chain). if (implMethod != null) { var entry = new DispatchMapEntry(); entry.InterfaceIndex = checked((short)i); entry.InterfaceMethodSlot = checked((short)j); entry.ImplementationMethodSlot = checked((short)VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, implMethod)); dispatchMapEntries.Add(entry); } } } } return dispatchMapEntries.ToArray(); }
/// <summary> /// Creates a special block that is marked as not allowing jumps in. /// This should not be used for rewriting BlockExpression itself, or /// anything else that supports jumping. /// </summary> private static Expression MakeBlock(ArrayBuilder<Expression> expressions) { return new SpilledExpressionBlock(expressions.ToArray()); }
private static RuntimeAssemblyName CreateRuntimeAssemblyNameFromMetadata( MetadataReader reader, ConstantStringValueHandle name, ushort majorVersion, ushort minorVersion, ushort buildNumber, ushort revisionNumber, ConstantStringValueHandle culture, IEnumerable<byte> 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; ArrayBuilder<byte> keyOrTokenArrayBuilder = new ArrayBuilder<byte>(); foreach (byte b in publicKeyOrToken) keyOrTokenArrayBuilder.Add(b); return new RuntimeAssemblyName( name.GetString(reader), new Version(majorVersion, minorVersion, buildNumber, revisionNumber), culture.GetStringOrNull(reader), assemblyNameFlags, keyOrTokenArrayBuilder.ToArray() ); }
public string[] BuildFileInfoMap(IEnumerable<DependencyNode> nodes) { ArrayBuilder<string> debugFileInfos = new ArrayBuilder<string>(); foreach (DependencyNode node in nodes) { if (node is INodeWithDebugInfo) { DebugLocInfo[] debugLocInfos = ((INodeWithDebugInfo)node).DebugLocInfos; if (debugLocInfos != null) { foreach (DebugLocInfo debugLocInfo in debugLocInfos) { string fileName = debugLocInfo.FileName; if (!_debugFileToId.ContainsKey(fileName)) { _debugFileToId.Add(fileName, debugFileInfos.Count); debugFileInfos.Add(fileName); } } } } } return debugFileInfos.Count > 0 ? debugFileInfos.ToArray() : null; }
public string[] BuildFileInfoMap(IEnumerable<DependencyNode> nodes) { // TODO: DebugInfo on Unix https://github.com/dotnet/corert/issues/608 if (_targetPlatform.OperatingSystem != TargetOS.Windows) return null; ArrayBuilder<string> debugFileInfos = new ArrayBuilder<string>(); foreach (DependencyNode node in nodes) { if (node is INodeWithDebugInfo) { DebugLocInfo[] debugLocInfos = ((INodeWithDebugInfo)node).DebugLocInfos; if (debugLocInfos != null) { foreach (DebugLocInfo debugLocInfo in debugLocInfos) { string fileName = debugLocInfo.FileName; if (!_debugFileToId.ContainsKey(fileName)) { _debugFileToId.Add(fileName, debugFileInfos.Count); debugFileInfos.Add(fileName); } } } } } return debugFileInfos.Count > 0 ? debugFileInfos.ToArray() : null; }
internal void EmitVariableAccess(LambdaCompiler lc, ReadOnlyCollection<ParameterExpression> vars) { if (NearestHoistedLocals != null && vars.Count > 0) { // Find what array each variable is on & its index var indexes = new ArrayBuilder<long>(vars.Count); foreach (ParameterExpression variable in vars) { // For each variable, find what array it's defined on ulong parents = 0; HoistedLocals locals = NearestHoistedLocals; while (!locals.Indexes.ContainsKey(variable)) { parents++; locals = locals.Parent; Debug.Assert(locals != null); } // combine the number of parents we walked, with the // real index of variable to get the index to emit. ulong index = (parents << 32) | (uint)locals.Indexes[variable]; indexes.UncheckedAdd((long)index); } EmitGet(NearestHoistedLocals.SelfVariable); lc.EmitConstantArray(indexes.ToArray()); lc.IL.Emit(OpCodes.Call, RuntimeOps_CreateRuntimeVariables_ObjectArray_Int64Array); } else { // No visible variables lc.IL.Emit(OpCodes.Call, RuntimeOps_CreateRuntimeVariables); } }
protected override MethodImplRecord[] ComputeVirtualMethodImplsForType() { ArrayBuilder<MethodImplRecord> records = new ArrayBuilder<MethodImplRecord>(); MetadataReader metadataReader = _module.MetadataReader; foreach (var methodImplHandle in _typeDefinition.GetMethodImplementations()) { MethodImplementation methodImpl = metadataReader.GetMethodImplementation(methodImplHandle); EntityHandle methodDeclCheckHandle = methodImpl.MethodDeclaration; HandleKind methodDeclHandleKind = methodDeclCheckHandle.Kind; // We want to check that the type is not an interface matches before actually getting the MethodDesc. // For MethodSpecifications we need to dereference that handle to the underlying member reference to // look at the owning type. if (methodDeclHandleKind == HandleKind.MethodSpecification) { methodDeclCheckHandle = metadataReader.GetMethodSpecification((MethodSpecificationHandle)methodDeclCheckHandle).Method; methodDeclHandleKind = methodDeclCheckHandle.Kind; } MetadataType owningType = null; switch (methodDeclHandleKind) { case HandleKind.MethodDefinition: owningType = ((MethodDesc)_module.GetObject(methodDeclCheckHandle)).OwningType as MetadataType; break; case HandleKind.MemberReference: EntityHandle owningTypeHandle = metadataReader.GetMemberReference((MemberReferenceHandle)methodDeclCheckHandle).Parent; owningType = _module.GetObject(owningTypeHandle) as MetadataType; break; default: Debug.Assert(false, "unexpected methodDeclHandleKind"); break; } if (!owningType.IsInterface) { MethodImplRecord newRecord = new MethodImplRecord(); newRecord.Decl = (MethodDesc)_module.GetObject(methodImpl.MethodDeclaration); newRecord.Body = (MethodDesc)_module.GetObject(methodImpl.MethodBody); records.Add(newRecord); } } return records.ToArray(); }
/// <summary> /// Parses the string '<paramref name="name"/>' and returns the type corresponding to the parsed type name. /// The type name string should be in the 'SerString' format as defined by the ECMA-335 standard. /// </summary> public static TypeDesc GetTypeByCustomAttributeTypeName(this ModuleDesc module, string name) { TypeDesc loadedType; StringBuilder genericTypeDefName = new StringBuilder(name.Length); var ch = name.Begin(); var nameEnd = name.End(); for (; ch < nameEnd; ++ch) { // Always pass escaped characters through. if (ch.Current == '\\') { genericTypeDefName.Append(ch.Current); ++ch; if (ch < nameEnd) { genericTypeDefName.Append(ch.Current); } continue; } // The type def name ends if // The start of a generic argument list if (ch.Current == '[') break; // Indication that the type is a pointer if (ch.Current == '*') break; // Indication that the type is a reference if (ch.Current == '&') break; // A comma that indicates that the rest of the name is an assembly reference if (ch.Current == ',') break; genericTypeDefName.Append(ch.Current); } ModuleDesc homeModule = module; AssemblyName homeAssembly = FindAssemblyIfNamePresent(name); if (homeAssembly != null) { homeModule = module.Context.ResolveAssembly(homeAssembly); } MetadataType typeDef = ResolveCustomAttributeTypeNameToTypeDesc(genericTypeDefName.ToString(), homeModule); ArrayBuilder<TypeDesc> genericArgs = new ArrayBuilder<TypeDesc>(); // Followed by generic instantiation parameters (but check for the array case) if (ch < nameEnd && ch.Current == '[' && (ch + 1) < nameEnd && (ch + 1).Current != ']' && (ch + 1).Current != ',') { ch++; // truncate the '[' var genericInstantiationEnd = ch + ReadTypeArgument(ch, nameEnd, true); // find the end of the instantiation list while (ch < genericInstantiationEnd) { if (ch.Current == ',') ch++; int argLen = ReadTypeArgument(ch, name.End(), false); string typeArgName; if (ch.Current == '[') { // This type argument name is stringified, // we need to remove the [] from around it ch++; typeArgName = StringIterator.Substring(ch, ch + (argLen - 2)); ch += argLen - 1; } else { typeArgName = StringIterator.Substring(ch, ch + argLen); ch += argLen; } TypeDesc argType = module.GetTypeByCustomAttributeTypeName(typeArgName); genericArgs.Add(argType); } Debug.Assert(ch == genericInstantiationEnd); ch++; loadedType = typeDef.MakeInstantiatedType(genericArgs.ToArray()); } else { // Non-generic type loadedType = typeDef; } // At this point the characters following may be any number of * characters to indicate pointer depth while (ch < nameEnd) { if (ch.Current == '*') { loadedType = loadedType.MakePointerType(); } else { break; } ch++; } // Followed by any number of "[]" or "[,*]" pairs to indicate arrays int commasSeen = 0; bool bracketSeen = false; while (ch < nameEnd) { if (ch.Current == '[') { ch++; commasSeen = 0; bracketSeen = true; } else if (ch.Current == ']') { if (!bracketSeen) break; ch++; if (commasSeen == 0) { loadedType = loadedType.MakeArrayType(); } else { loadedType = loadedType.MakeArrayType(commasSeen + 1); } bracketSeen = false; } else if (ch.Current == ',') { if (!bracketSeen) break; ch++; commasSeen++; } else { break; } } // Followed by at most one & character to indicate a byref. if (ch < nameEnd) { if (ch.Current == '&') { loadedType = loadedType.MakeByRefType(); ch++; } } return loadedType; }