Esempio n. 1
0
        public InterceptorWrapperCollection(Type classType, Type proxyType)
        {
            if (classType == null)
            {
                throw new ArgumentNullException(nameof(classType));
            }

            if (proxyType == null)
            {
                throw new ArgumentNullException(nameof(proxyType));
            }

            _wrappers = new Dictionary <int, InterceptorWrapper>();
            SetClassInterceptors(_wrappers, classType);
            var nonInterceptAttribute = typeof(NonInterceptAttribute);

            foreach (var methodHandle in HandleCollection.GetHandles(proxyType.MetadataToken))
            {
                var method = MethodBase.GetMethodFromHandle(methodHandle);
                if (!method.IsDefined(nonInterceptAttribute))
                {
                    var(callingMethodInterceptors, calledMethodInterceptors, exceptionInterceptor) = GetMemberInterceptors(method);
                    _wrappers.Add(method.MetadataToken, new InterceptorWrapper
                    {
                        CallingInterceptors  = new List <ICallingInterceptor>(callingMethodInterceptors),
                        CalledInterceptors   = new List <ICalledInterceptor>(calledMethodInterceptors),
                        ExceptionInterceptor = exceptionInterceptor
                    });
                }
            }
        }
Esempio n. 2
0
        } // Read

        public static uint Read(this NativeReader reader, uint offset, out HandleCollection values)
        {
            values = new HandleCollection(reader, offset);
            uint count;

            offset = reader.DecodeUnsigned(offset, out count);
            for (uint i = 0; i < count; ++i)
            {
                offset = reader.SkipInteger(offset);
            }
            return(offset);
        } // Read
Esempio n. 3
0
        public TesterClass(IntPtr[] deps)
        {
            _nextHandle = IntPtr.Add(_nextHandle, 1);
            Handle      = _nextHandle;
            var _deps = new HandleCollection <string, IntPtr>();

            foreach (var dep in deps)
            {
                _deps.Add(typeof(TesterClass).Name, dep);
            }
            UnmanagedObjectLifecycle.Register(typeof(TesterClass).Name, Handle, DestroyObject, _deps);
        }
Esempio n. 4
0
        public static Handle[] ToArray(this HandleCollection collection)
        {
            int count = collection.Count;

            Handle[] result = new Handle[count];
            int      i      = 0;

            foreach (Handle element in collection)
            {
                result[i++] = element;
            }
            Debug.Assert(i == count);
            return(result);
        }
Esempio n. 5
0
        /// <summary>
        /// Emit parenthesized method argument type list with parameter names.
        /// </summary>
        /// <param name="methodHandle">Method handle to use for parameter formatting</param>
        private void EmitMethodParameters(MethodHandle methodHandle)
        {
            bool TryGetNextParameter(ref ParameterHandleCollection.Enumerator enumerator, out Parameter parameter)
            {
                bool hasNext = enumerator.MoveNext();

                parameter = hasNext ? enumerator.Current.GetParameter(_metadataReader) : default;
                return(hasNext);
            }

            Method           method     = methodHandle.GetMethod(_metadataReader);
            HandleCollection typeVector = method.Signature.GetMethodSignature(_metadataReader).Parameters;

            ParameterHandleCollection.Enumerator parameters = method.Parameters.GetEnumerator();

            bool hasParameter = TryGetNextParameter(ref parameters, out Parameter parameter);

            if (hasParameter && parameter.Sequence == 0)
            {
                hasParameter = TryGetNextParameter(ref parameters, out parameter);
            }

            _outputBuilder.Append('(');

            uint typeIndex = 0;

            foreach (Handle type in typeVector)
            {
                if (typeIndex != 0)
                {
                    _outputBuilder.Append(", ");
                }

                EmitTypeName(type, namespaceQualified: false);

                if (++typeIndex == parameter.Sequence && hasParameter)
                {
                    string name = parameter.Name.GetConstantStringValue(_metadataReader).Value;
                    hasParameter = TryGetNextParameter(ref parameters, out parameter);

                    if (!string.IsNullOrEmpty(name))
                    {
                        _outputBuilder.Append(' ');
                        _outputBuilder.Append(name);
                    }
                }
            }

            _outputBuilder.Append(')');
        }
Esempio n. 6
0
            public static Handle GetHandleAt(HandleCollection collection, int index)
            {
                int currentIndex = 0;

                foreach (var currentArg in collection)
                {
                    if (currentIndex == index)
                    {
                        return(currentArg);
                    }
                    currentIndex++;
                }

                Debug.Assert(false);
                return(default(Handle));
            }
Esempio n. 7
0
        /// <summary>
        /// Emit comma-separated list of type names into the output string builder.
        /// </summary>
        /// <param name="typeVector">Enumeration of type handles to output</param>
        private void EmitTypeVector(HandleCollection typeVector)
        {
            bool first = true;

            foreach (Handle handle in typeVector)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    _outputBuilder.Append(", ");
                }
                EmitTypeName(handle, namespaceQualified: false);
            }
        }
Esempio n. 8
0
        public IntPtrConstructorMethodInvoker(MetadataReader reader, MethodHandle methodHandle)
        {
            // Since we control the definition of System.IntPtr, we only do enough analysis of the signature to disambiguate the constructors we support.
            _id = IntPtrConstructorId.None;
            Method           method = methodHandle.GetMethod(reader);
            HandleCollection parameterTypeSignatureHandles = method.Signature.GetMethodSignature(reader).Parameters;

            if (parameterTypeSignatureHandles.Count == 1)
            {
                HandleCollection.Enumerator enumerator = parameterTypeSignatureHandles.GetEnumerator();
                enumerator.MoveNext();
                Handle parameterTypeHandle = enumerator.Current;

                // If any parameter is a pointer type, bail as we don't support Invokes on pointers.
                if (parameterTypeHandle.HandleType != HandleType.TypeDefinition)
                {
                    throw new PlatformNotSupportedException(SR.PlatformNotSupported_PointerArguments);
                }

                TypeDefinition typeDefinition = parameterTypeHandle.ToTypeDefinitionHandle(reader).GetTypeDefinition(reader);
                String         name           = typeDefinition.Name.GetString(reader);
                switch (name)
                {
                case "Int32":
                    _id = IntPtrConstructorId.Int32;
                    break;

                case "Int64":
                    _id = IntPtrConstructorId.Int64;
                    break;

                case "UInt32":
                    _id = IntPtrConstructorId.UInt32;
                    break;

                case "UInt64":
                    _id = IntPtrConstructorId.UInt64;
                    break;

                default:
                    break;
                }
            }
        }
        private Type GenerateProxyType(Type interfaceType, Type classType)
        {
            var context = new GeneratorTypeContext
            {
                ModuleBuilder = _moduleBuilder,
                ClassType     = classType,
                InterfaceType = interfaceType
            };

            DefineTypeOperator.Generate(context);
            DefineFieldsOperator.Generate(context);

            ImplementConstructorsOperator.Generate(context);
            ImplementMethodsOperator.Generate(context);

            var proxyType = context.TypeBuilder.CreateTypeInfo();

            HandleCollection.AddHandles(proxyType.MetadataToken, context.MethodHandles);
            return(proxyType);
        }
Esempio n. 10
0
        /// <summary>
        /// Opens a document stored in the old QuickRoute XML file format. This version can't save documents in this file format.
        /// </summary>
        /// <param name="fileName">The file name of the QuickRoute 1.0 xml document.</param>
        /// <param name="settings">The document settings to apply.</param>
        /// <returns></returns>
        public static Document OpenFromXml(string fileName, DocumentSettings settings)
        {
            XmlTextReader reader = null;

              RouteSegment rs = new RouteSegment();
              HandleCollection handles = new HandleCollection();
              Map map;

              try
              {

            reader = new XmlTextReader(fileName);
            reader.WhitespaceHandling = WhitespaceHandling.None;

            reader.ReadStartElement("QuickRoute");

            reader.ReadStartElement("Route");

            while (reader.Read() && reader.NodeType != XmlNodeType.EndElement)
            {
              while (reader.NodeType != XmlNodeType.Element) reader.Read();
              Waypoint t = new Waypoint();
              t.Time = DateTime.Parse(reader.GetAttribute("time"));
              t.LongLat = new LongLat();
              t.LongLat.Longitude = double.Parse(reader.GetAttribute("longitude"));
              t.LongLat.Latitude = double.Parse(reader.GetAttribute("latitude"));
              t.Altitude = double.Parse(reader.GetAttribute("altitude"));
              t.HeartRate = int.Parse(reader.GetAttribute("heartRate"));
              rs.Waypoints.Add(t);
            }
            reader.ReadEndElement();

            reader.ReadStartElement("Markers");
            while (reader.Name == "Handle")
            {
              reader.Read();
              Handle h = new Handle();
              h.ParameterizedLocation = new ParameterizedLocation(0, double.Parse(reader.GetAttribute("value")));
              reader.Read();
              double x = double.Parse(reader.GetAttribute("x"));
              double y = double.Parse(reader.GetAttribute("y"));
              h.Location = new PointD(x, y);
              reader.Read();
              h.TransformationMatrix = new GeneralMatrix(3, 3);
              h.MarkerDrawer = (new ApplicationSettings()).DefaultDocumentSettings.DefaultSessionSettings.MarkerDrawers[MarkerType.Handle];
              for (int row = 0; row < 3; row++)
              {
            for (int col = 0; col < 3; col++)
            {
              reader.Read();
              h.TransformationMatrix.SetElement(row, col, double.Parse(reader.GetAttribute("value")));
            }
              }
              reader.Read();
              reader.ReadEndElement();
              reader.ReadEndElement();
              handles.Add(h);
            }
            reader.ReadEndElement();

            map = new Map(Base64StringToBitmap(reader.ReadElementContentAsString()));

              }
              catch (Exception ex)
              {
            if (reader != null) reader.Close();
            throw new Exception(ex.Message);
              }
              reader.Close();

              List<RouteSegment> routeSegments = new List<RouteSegment>();
              routeSegments.Add(rs);
              Document doc = new Document(map, new Route(routeSegments), new LapCollection(), null, settings);
              foreach (var h in handles)
              {
            doc.Sessions[0].AddHandle(h);
              }
              doc.FileFormat = QuickRouteFileFormat.Xml;
              doc.Initialize();
              UpdateDocumentToCurrentVersion(doc);
              return doc;
        }
Esempio n. 11
0
 /// <summary>
 /// Emit angle-bracketed list of type / method generic arguments.
 /// </summary>
 /// <param name="genericArguments">Collection of generic argument type handles</param>
 private void EmitGenericArguments(HandleCollection genericArguments)
 {
     _outputBuilder.Append('[');
     EmitTypeVector(genericArguments);
     _outputBuilder.Append(']');
 }
Esempio n. 12
0
 internal VariableManager()
 {
     m_variableHandles = new HandleCollection <Object>();
 }
Esempio n. 13
0
        private static Array TryParseConstantArray(this Handle handle, MetadataReader reader, out Exception exception)
        {
            exception = null;

            HandleType handleType = handle.HandleType;

            switch (handleType)
            {
            case HandleType.ConstantBooleanArray:
                return(handle.ToConstantBooleanArrayHandle(reader).GetConstantBooleanArray(reader).Value.ToArray());

            case HandleType.ConstantCharArray:
                return(handle.ToConstantCharArrayHandle(reader).GetConstantCharArray(reader).Value.ToArray());

            case HandleType.ConstantByteArray:
                return(handle.ToConstantByteArrayHandle(reader).GetConstantByteArray(reader).Value.ToArray());

            case HandleType.ConstantSByteArray:
                return(handle.ToConstantSByteArrayHandle(reader).GetConstantSByteArray(reader).Value.ToArray());

            case HandleType.ConstantInt16Array:
                return(handle.ToConstantInt16ArrayHandle(reader).GetConstantInt16Array(reader).Value.ToArray());

            case HandleType.ConstantUInt16Array:
                return(handle.ToConstantUInt16ArrayHandle(reader).GetConstantUInt16Array(reader).Value.ToArray());

            case HandleType.ConstantInt32Array:
                return(handle.ToConstantInt32ArrayHandle(reader).GetConstantInt32Array(reader).Value.ToArray());

            case HandleType.ConstantUInt32Array:
                return(handle.ToConstantUInt32ArrayHandle(reader).GetConstantUInt32Array(reader).Value.ToArray());

            case HandleType.ConstantInt64Array:
                return(handle.ToConstantInt64ArrayHandle(reader).GetConstantInt64Array(reader).Value.ToArray());

            case HandleType.ConstantUInt64Array:
                return(handle.ToConstantUInt64ArrayHandle(reader).GetConstantUInt64Array(reader).Value.ToArray());

            case HandleType.ConstantSingleArray:
                return(handle.ToConstantSingleArrayHandle(reader).GetConstantSingleArray(reader).Value.ToArray());

            case HandleType.ConstantDoubleArray:
                return(handle.ToConstantDoubleArrayHandle(reader).GetConstantDoubleArray(reader).Value.ToArray());

            case HandleType.ConstantEnumArray:
                return(TryParseConstantEnumArray(handle.ToConstantEnumArrayHandle(reader), reader, out exception));

            case HandleType.ConstantStringArray:
            {
                HandleCollection constantHandles = handle.ToConstantStringArrayHandle(reader).GetConstantStringArray(reader).Value;
                string[]         elements        = new string[constantHandles.Count];
                int i = 0;
                foreach (Handle constantHandle in constantHandles)
                {
                    object elementValue;
                    exception = constantHandle.TryParseConstantValue(reader, out elementValue);
                    if (exception != null)
                    {
                        return(null);
                    }
                    elements[i] = (string)elementValue;
                    i++;
                }
                return(elements);
            }

            case HandleType.ConstantHandleArray:
            {
                HandleCollection constantHandles = handle.ToConstantHandleArrayHandle(reader).GetConstantHandleArray(reader).Value;
                object[]         elements        = new object[constantHandles.Count];
                int i = 0;
                foreach (Handle constantHandle in constantHandles)
                {
                    exception = constantHandle.TryParseConstantValue(reader, out elements[i]);
                    if (exception != null)
                    {
                        return(null);
                    }
                    i++;
                }
                return(elements);
            }

            default:
                throw new BadImageFormatException();
            }
        }
Esempio n. 14
0
        } // Read

        public static uint Read(this NativeReader reader, uint offset, out HandleCollection values)
        {
            values = new HandleCollection(reader, offset);
            uint count;
            offset = reader.DecodeUnsigned(offset, out count);
            for (uint i = 0; i < count; ++i)
            {
                offset = reader.SkipInteger(offset);
            }
            return offset;
        } // Read
Esempio n. 15
0
        public InterceptorWrapperCollection(Type interfaceType, Type classType, Type proxyType)
        {
            if (interfaceType == null)
            {
                throw new ArgumentNullException(nameof(interfaceType));
            }

            if (classType == null)
            {
                throw new ArgumentNullException(nameof(classType));
            }

            if (proxyType == null)
            {
                throw new ArgumentNullException(nameof(proxyType));
            }

            _wrappers = new Dictionary <int, InterceptorWrapper>();
            SetClassInterceptors(_wrappers, classType);
            if (!interfaceType.IsDefined(typeof(NonInterceptAttribute)))
            {
                var(callingInterceptors, calledInterceptors) = GetMemberInterceptorsWithoutException(interfaceType);
                if (_wrappers.ContainsKey(0))
                {
                    _wrappers[0].CallingInterceptors.AddRange(callingInterceptors);
                    _wrappers[0].CalledInterceptors.AddRange(calledInterceptors);
                    if (_wrappers[0].ExceptionInterceptor == null)
                    {
                        _wrappers[0].ExceptionInterceptor = interfaceType.GetCustomAttribute <ExceptionInterceptAttribute>();
                    }
                }
                else
                {
                    _wrappers.Add(0, new InterceptorWrapper
                    {
                        CallingInterceptors  = new List <ICallingInterceptor>(callingInterceptors),
                        CalledInterceptors   = new List <ICalledInterceptor>(calledInterceptors),
                        ExceptionInterceptor = interfaceType.GetCustomAttribute <ExceptionInterceptAttribute>()
                    });
                }
            }

            var nonInterceptAttribute = typeof(NonInterceptAttribute);
            var interfaceMethods      = interfaceType.GetMethods(
                BindingFlags.Public |
                BindingFlags.Instance |
                BindingFlags.DeclaredOnly
                );

            foreach (var methodHandle in HandleCollection.GetHandles(proxyType.MetadataToken))
            {
                var method = MethodBase.GetMethodFromHandle(methodHandle);
                if (!method.IsDefined(nonInterceptAttribute))
                {
                    var(callingMethodInterceptors, calledMethodInterceptors, exceptionMethodInterceptor) = GetMemberInterceptors(method);
                    var wrapper = new InterceptorWrapper
                    {
                        CallingInterceptors  = new List <ICallingInterceptor>(callingMethodInterceptors),
                        CalledInterceptors   = new List <ICalledInterceptor>(calledMethodInterceptors),
                        ExceptionInterceptor = exceptionMethodInterceptor
                    };

                    foreach (var interfaceMethod in interfaceMethods)
                    {
                        if (method.Name == interfaceMethod.Name || method.Name == interfaceType.FullName + "." + interfaceMethod.Name)
                        {
                            var(callingInterfaceMethodInterceptors, calledInterfaceMethodInterceptors) =
                                GetMemberInterceptorsWithoutException(interfaceMethod);
                            wrapper.CallingInterceptors.AddRange(callingInterfaceMethodInterceptors);
                            wrapper.CalledInterceptors.AddRange(calledInterfaceMethodInterceptors);
                            if (wrapper.ExceptionInterceptor == null) // 接口方法的优先级较低
                            {
                                wrapper.ExceptionInterceptor = interfaceMethod.GetCustomAttribute <ExceptionInterceptAttribute>();
                            }

                            break;
                        }
                    }

                    _wrappers.Add(method.MetadataToken, wrapper);
                }
            }
        }
        private static Session ReadSession(BinaryReader reader, int length)
        {
            List<DateTime> mapReadingList = null;
              Route route = null;
              HandleCollection handles = null;
              LongLat projectionOrigin = null;
              LapCollection laps = null;
              var startPos = reader.BaseStream.Position;
              SessionInfo sessionInfo = null;
              DateTime lastTime;
              while (reader.BaseStream.Position < startPos + length)
              {
            var tag = (Tags)reader.ReadByte();
            var tagLength = Convert.ToInt32(reader.ReadUInt32());
            switch (tag)
            {
              case Tags.Route:
            var attributes = reader.ReadUInt16();
            var extraWaypointAttributesLength = reader.ReadUInt16();
            var routeSegments = new List<RouteSegment>();
            var segmentCount = reader.ReadUInt32();
            lastTime = DateTime.MinValue;
            for (var i = 0; i < segmentCount; i++)
            {
              var rs = new RouteSegment();
              var waypointCount = reader.ReadUInt32();
              for (var j = 0; j < waypointCount; j++)
              {
                var w = new Waypoint();
                w.LongLat = ReadLongLat(reader);
                w.Time = ReadTime(lastTime, reader);
                lastTime = w.Time;
                if ((attributes & (UInt16)WaypointAttribute.HeartRate) == (UInt16)WaypointAttribute.HeartRate)
                {
                  w.HeartRate = reader.ReadByte();
                }
                if ((attributes & (UInt16)WaypointAttribute.Altitude) == (UInt16)WaypointAttribute.Altitude)
                {
                  w.Altitude = reader.ReadInt16();
                }
                reader.BaseStream.Position += extraWaypointAttributesLength; // for forward compatibility
                rs.Waypoints.Add(w);
              }
              routeSegments.Add(rs);
            }
            route = new Route(routeSegments);
            break;

              case Tags.Handles:
            handles = new HandleCollection();
            var handleCount = reader.ReadUInt32();
            var handleMarkerDrawer = SessionSettings.CreateDefaultMarkerDrawers()[MarkerType.Handle];
            for (var i = 0; i < handleCount; i++)
            {
              var handle = new Handle();
              // transformation matrix
              handle.TransformationMatrix = new GeneralMatrix(3, 3);
              for (var j = 0; j < 9; j++)
              {
                handle.TransformationMatrix.SetElement(j / 3, j % 3, reader.ReadDouble());
              }
              // parameterized location
              var segmentIndex = Convert.ToInt32(reader.ReadUInt32());
              var value = reader.ReadDouble();
              handle.ParameterizedLocation = new ParameterizedLocation(segmentIndex, value);

              // pixel location
              handle.Location = new PointD(reader.ReadDouble(), reader.ReadDouble());
              // type
              handle.Type = (Handle.HandleType)reader.ReadInt16();
              // use default marker drawer
              handle.MarkerDrawer = handleMarkerDrawer;

              handles.Add(handle);
            }
            break;

              case Tags.ProjectionOrigin:
            projectionOrigin = ReadLongLat(reader);
            break;

              case Tags.Laps:
            laps = new LapCollection();
            var lapCount = reader.ReadUInt32();
            for (var i = 0; i < lapCount; i++)
            {
              var lap = new Lap();
              lap.Time = DateTime.FromBinary(reader.ReadInt64());
              lap.LapType = (LapType)reader.ReadByte();
              laps.Add(lap);
            }
            break;

              case Tags.SessionInfo:
            sessionInfo = new SessionInfo();
            sessionInfo.Person = new SessionPerson();
            sessionInfo.Person.Name = ReadString(reader);
            sessionInfo.Person.Club = ReadString(reader);
            sessionInfo.Person.Id = reader.ReadUInt32();
            sessionInfo.Description = ReadString(reader);
            // when more fields are added, check so that tagLength is not passed
            break;

              case Tags.MapReadingInfo:
            mapReadingList = new List<DateTime>();
            lastTime = DateTime.MinValue;
            var startPosition = reader.BaseStream.Position;
            while (reader.BaseStream.Position - startPosition < tagLength)
            {
              var time = ReadTime(lastTime, reader);
              mapReadingList.Add(time);
              lastTime = time;
            }
            break;

              default:
            reader.BaseStream.Position += tagLength;
            break;
            }
              }

              if(mapReadingList != null && route != null) route = new Route(Route.AddMapReadingWaypoints(route.Segments, mapReadingList));
              var session = new Session(
            route,
            laps,
            new Size(0, 0),
            handles != null && handles.Count > 0 ? handles[0].TransformationMatrix : null,
            projectionOrigin,
            new SessionSettings());
              if (handles != null)
              {
            foreach (var h in handles)
            {
              session.AddHandle(h);
            }
              }
              if (sessionInfo != null) session.SessionInfo = sessionInfo;

              return session;
        }