Ejemplo n.º 1
0
        static bool ImplementsInterface(TypeInfo pObjType, TypeInfo pTargetType)
        {
            Debug.Assert(!pTargetType.IsArray, "did not expect array type");
            Debug.Assert(pTargetType.IsInterface, "IsInstanceOfInterface called with non-interface EEType");

            foreach (var pInterfaceType in pObjType.ImplementedInterfaces)
            {
                if (AreTypesEquivalentInternal(pInterfaceType.GetTypeInfo(), pTargetType))
                {
                    return(true);
                }
            }

            // We did not find the interface type in the list of supported interfaces. There's still one
            // chance left: if the target interface is generic and one or more of its type parameters is co or
            // contra variant then the object can still match if it implements a different instantiation of
            // the interface with type compatible generic arguments.
            //
            // An additional edge case occurs because of array covariance. This forces us to treat any generic
            // interfaces implemented by arrays as covariant over their one type parameter.
            // if (pTargetType.HasGenericVariance || (fArrayCovariance && pTargetType.IsGenericType))
            //
            if (pTargetType.IsGenericType)
            {
                bool fArrayCovariance   = pObjType.IsArray;
                Type pTargetGenericType = pTargetType.GetGenericTypeDefinition();

                // Fetch the instantiations lazily only once we get a potential match
                Type[] pTargetInstantiation        = null;
                Type[] pTargetGenericInstantiation = null;

                foreach (var pInterface in pObjType.ImplementedInterfaces)
                {
                    TypeInfo pInterfaceType = pInterface.GetTypeInfo();

                    // We can ignore interfaces which are not also marked as having generic variance
                    // unless we're dealing with array covariance.
                    // if (pInterfaceType.HasGenericVariance || (fArrayCovariance && pInterfaceType.IsGenericType))

                    if (!pInterfaceType.IsGenericType)
                    {
                        continue;
                    }

                    // If the generic types aren't the same then the types aren't compatible.
                    if (!pInterfaceType.GetGenericTypeDefinition().Equals(pTargetGenericType))
                    {
                        continue;
                    }

                    Type[] pInterfaceInstantiation = pInterfaceType.GenericTypeArguments;

                    if (pTargetInstantiation == null)
                    {
                        pTargetInstantiation = pTargetType.GenericTypeArguments;

                        if (!fArrayCovariance)
                        {
                            pTargetGenericInstantiation = pTargetGenericType.GetTypeInfo().GenericTypeParameters;
                        }
                    }

                    // Compare the instantiations to see if they're compatible taking variance into account.
                    if (TypeParametersAreCompatible(pInterfaceInstantiation,
                                                    pTargetInstantiation,
                                                    pTargetGenericInstantiation,
                                                    fArrayCovariance))
                    {
                        return(true);
                    }

                    if (fArrayCovariance)
                    {
                        Debug.Assert(pInterfaceInstantiation.Length == 1, "arity mismatch for array generic interface");
                        Debug.Assert(pTargetInstantiation.Length == 1, "arity mismatch for array generic interface");

                        // Special case for generic interfaces on arrays. Arrays of integral types (including enums)
                        // can be cast to generic interfaces over the integral types of the same size. For example
                        // int[] . IList<uint>.
                        if (ArePrimitveTypesEquivalentSize(pInterfaceInstantiation[0].GetTypeInfo(),
                                                           pTargetInstantiation[0].GetTypeInfo()))
                        {
                            // We have checked that the interface type definition matches above. The checks are ordered differently
                            // here compared with rtm\system\runtime\typecast.cs version because of TypeInfo does not let us do
                            // the HasGenericVariance optimization.
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 2
0
        private void ProcessListeningThread(object state)
        {
            string processId     = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture);
            string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();

            // Logging.
            _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                 "Listener thread started on Process {0} in AppDomainName {1}.", processId, appDomainName);
            PSEtwLog.LogOperationalInformation(
                PSEventId.NamedPipeIPC_ServerListenerStarted, PSOpcode.Open, PSTask.NamedPipe,
                PSKeyword.UseAlwaysOperational,
                processId, appDomainName);

            Exception ex       = null;
            string    userName = string.Empty;
            bool      restartListenerThread = true;

            // Wait for connection.
            try
            {
                // Begin listening for a client connect.
                this.WaitForConnection();

                try
                {
#if UNIX
                    userName = System.Environment.UserName;
#else
                    userName = WindowsIdentity.GetCurrent().Name;
#endif
                }
                catch (System.Security.SecurityException) { }

                // Logging.
                _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                     "Client connection started on Process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
                PSEtwLog.LogOperationalInformation(
                    PSEventId.NamedPipeIPC_ServerConnect, PSOpcode.Connect, PSTask.NamedPipe,
                    PSKeyword.UseAlwaysOperational,
                    processId, appDomainName, userName);

                // Create reader/writer streams.
                TextReader           = new StreamReader(Stream);
                TextWriter           = new StreamWriter(Stream);
                TextWriter.AutoFlush = true;
            }
            catch (Exception e)
            {
                ex = e;
            }

            if (ex != null)
            {
                // Error during connection handling.  Don't try to restart listening thread.
                string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
                _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                     "Unexpected error in listener thread on process {0} in AppDomainName {1}.  Error Message: {2}", processId, appDomainName, errorMessage);
                PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
                                             PSKeyword.UseAlwaysOperational,
                                             processId, appDomainName, errorMessage);

                Dispose();
                return;
            }

            // Start server session on new connection.
            ex = null;
            try
            {
                Action <RemoteSessionNamedPipeServer> clientConnectCallback = state as Action <RemoteSessionNamedPipeServer>;
                Dbg.Assert(clientConnectCallback != null, "Client callback should never be null.");

                // Handle a new client connect by making the callback.
                // The callback must handle all exceptions except
                // for a named pipe disposed or disconnected exception
                // which propagates up to the thread listener loop.
                clientConnectCallback(this);
            }
            catch (IOException)
            {
                // Expected connection terminated.
            }
            catch (ObjectDisposedException)
            {
                // Expected from PS transport close/dispose.
            }
            catch (Exception e)
            {
                ex = e;
                restartListenerThread = false;
            }

            // Logging.
            _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                 "Client connection ended on process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
            PSEtwLog.LogOperationalInformation(
                PSEventId.NamedPipeIPC_ServerDisconnect, PSOpcode.Close, PSTask.NamedPipe,
                PSKeyword.UseAlwaysOperational,
                processId, appDomainName, userName);

            if (ex == null)
            {
                // Normal listener exit.
                _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                     "Listener thread ended on process {0} in AppDomainName {1}.", processId, appDomainName);
                PSEtwLog.LogOperationalInformation(PSEventId.NamedPipeIPC_ServerListenerEnded, PSOpcode.Close, PSTask.NamedPipe,
                                                   PSKeyword.UseAlwaysOperational,
                                                   processId, appDomainName);
            }
            else
            {
                // Unexpected error.
                string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
                _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
                                     "Unexpected error in listener thread on process {0} in AppDomainName {1}.  Error Message: {2}", processId, appDomainName, errorMessage);
                PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
                                             PSKeyword.UseAlwaysOperational,
                                             processId, appDomainName, errorMessage);
            }

            lock (_syncObject)
            {
                IsListenerRunning = false;
            }

            // Ensure this named pipe server object is disposed.
            Dispose();

            ListenerEnded.SafeInvoke(
                this,
                new ListenerEndedEventArgs(ex, restartListenerThread));
        }
        /// <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.
        /// This is the inverse of what <see cref="CustomAttributeTypeNameFormatter"/> does.
        /// </summary>
        public static TypeDesc GetTypeByCustomAttributeTypeName(this ModuleDesc module, string name, bool throwIfNotFound = true)
        {
            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, throwIfNotFound);

            if (typeDef == null)
            {
                return(null);
            }

            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, throwIfNotFound);
                    if (argType == null)
                    {
                        return(null);
                    }
                    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);
        }
Ejemplo n.º 4
0
 //
 // Returns the native layout info reader
 //
 internal unsafe NativeReader GetNativeLayoutInfoReader(RuntimeSignature signature)
 {
     Debug.Assert(signature.IsNativeLayoutSignature);
     return GetNativeLayoutInfoReader(new TypeManagerHandle(signature.ModuleHandle));
 }
Ejemplo n.º 5
0
        private void ImportCall(ILOpcode opcode, int token)
        {
            // We get both the canonical and runtime determined form - JitInterface mostly operates
            // on the canonical form.
            var runtimeDeterminedMethod = (MethodDesc)_methodIL.GetObject(token);
            var method = (MethodDesc)_canonMethodIL.GetObject(token);

            if (method.IsRawPInvoke())
            {
                // Raw P/invokes don't have any dependencies.
                return;
            }

            string reason = null;

            switch (opcode)
            {
            case ILOpcode.newobj:
                reason = "newobj"; break;

            case ILOpcode.call:
                reason = "call"; break;

            case ILOpcode.callvirt:
                reason = "callvirt"; break;

            case ILOpcode.ldftn:
                reason = "ldftn"; break;

            case ILOpcode.ldvirtftn:
                reason = "ldvirtftn"; break;

            default:
                Debug.Assert(false); break;
            }

            if (opcode == ILOpcode.newobj)
            {
                TypeDesc owningType = runtimeDeterminedMethod.OwningType;
                if (owningType.IsString)
                {
                    // String .ctor handled specially below
                }
                else if (owningType.IsGCPointer)
                {
                    if (owningType.IsRuntimeDeterminedSubtype)
                    {
                        _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, owningType), reason);
                    }
                    else
                    {
                        _dependencies.Add(_factory.ConstructedTypeSymbol(owningType), reason);
                    }

                    if (owningType.IsMdArray)
                    {
                        _dependencies.Add(GetHelperEntrypoint(ReadyToRunHelper.NewMultiDimArr_NonVarArg), reason);
                        return;
                    }
                    else
                    {
                        _dependencies.Add(GetHelperEntrypoint(ReadyToRunHelper.NewObject), reason);
                    }
                }

                if (owningType.IsDelegate)
                {
                    // If this is a verifiable delegate construction sequence, the previous instruction is a ldftn/ldvirtftn
                    if (_previousInstructionOffset >= 0 && _ilBytes[_previousInstructionOffset] == (byte)ILOpcode.prefix1)
                    {
                        // TODO: for ldvirtftn we need to also check for the `dup` instruction, otherwise this is a normal newobj.

                        ILOpcode previousOpcode = (ILOpcode)(0x100 + _ilBytes[_previousInstructionOffset + 1]);
                        if (previousOpcode == ILOpcode.ldvirtftn || previousOpcode == ILOpcode.ldftn)
                        {
                            int                  delTargetToken    = ReadILTokenAt(_previousInstructionOffset + 2);
                            var                  delTargetMethod   = (MethodDesc)_methodIL.GetObject(delTargetToken);
                            TypeDesc             canonDelegateType = method.OwningType.ConvertToCanonForm(CanonicalFormKind.Specific);
                            DelegateCreationInfo info = _compilation.GetDelegateCtor(canonDelegateType, delTargetMethod, previousOpcode == ILOpcode.ldvirtftn);

                            if (info.NeedsRuntimeLookup)
                            {
                                _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.DelegateCtor, info), reason);
                            }
                            else
                            {
                                _dependencies.Add(_factory.ReadyToRunHelper(ReadyToRunHelperId.DelegateCtor, info), reason);
                            }

                            return;
                        }
                    }
                }
            }

            if (method.OwningType.IsDelegate && method.Name == "Invoke" &&
                opcode != ILOpcode.ldftn && opcode != ILOpcode.ldvirtftn)
            {
                // This call is expanded as an intrinsic; it's not an actual function call.
                // Before codegen realizes this is an intrinsic, it might still ask questions about
                // the vtable of this virtual method, so let's make sure it's marked in the scanner's
                // dependency graph.
                _dependencies.Add(_factory.VTable(method.OwningType), reason);
                return;
            }

            if (method.IsIntrinsic)
            {
                if (IsRuntimeHelpersInitializeArray(method))
                {
                    if (_previousInstructionOffset >= 0 && _ilBytes[_previousInstructionOffset] == (byte)ILOpcode.ldtoken)
                    {
                        return;
                    }
                }

                if (IsRuntimeTypeHandleGetValueInternal(method))
                {
                    if (_previousInstructionOffset >= 0 && _ilBytes[_previousInstructionOffset] == (byte)ILOpcode.ldtoken)
                    {
                        return;
                    }
                }

                if (IsActivatorDefaultConstructorOf(method))
                {
                    if (runtimeDeterminedMethod.IsRuntimeDeterminedExactMethod)
                    {
                        _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.DefaultConstructor, runtimeDeterminedMethod.Instantiation[0]), reason);
                    }
                    else
                    {
                        MethodDesc ctor = method.Instantiation[0].GetDefaultConstructor();
                        if (ctor == null)
                        {
                            MetadataType activatorType        = _compilation.TypeSystemContext.SystemModule.GetKnownType("System", "Activator");
                            MetadataType classWithMissingCtor = activatorType.GetKnownNestedType("ClassWithMissingConstructor");
                            ctor = classWithMissingCtor.GetParameterlessConstructor();
                        }
                        _dependencies.Add(_factory.CanonicalEntrypoint(ctor), reason);
                    }

                    return;
                }

                if (method.OwningType.IsByReferenceOfT && (method.IsConstructor || method.Name == "get_Value"))
                {
                    return;
                }

                if (IsEETypePtrOf(method))
                {
                    if (runtimeDeterminedMethod.IsRuntimeDeterminedExactMethod)
                    {
                        _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, runtimeDeterminedMethod.Instantiation[0]), reason);
                    }
                    else
                    {
                        _dependencies.Add(_factory.ConstructedTypeSymbol(method.Instantiation[0]), reason);
                    }
                    return;
                }
            }

            TypeDesc exactType = method.OwningType;

            if (method.IsNativeCallable && (opcode != ILOpcode.ldftn && opcode != ILOpcode.ldvirtftn))
            {
                ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramNativeCallable, method);
            }

            bool resolvedConstraint    = false;
            bool forceUseRuntimeLookup = false;

            MethodDesc methodAfterConstraintResolution = method;

            if (_constrained != null)
            {
                // We have a "constrained." call.  Try a partial resolve of the constraint call.  Note that this
                // will not necessarily resolve the call exactly, since we might be compiling
                // shared generic code - it may just resolve it to a candidate suitable for
                // JIT compilation, and require a runtime lookup for the actual code pointer
                // to call.

                TypeDesc constrained = _constrained;
                if (constrained.IsRuntimeDeterminedSubtype)
                {
                    constrained = constrained.ConvertToCanonForm(CanonicalFormKind.Specific);
                }

                MethodDesc directMethod = constrained.GetClosestDefType().TryResolveConstraintMethodApprox(method.OwningType, method, out forceUseRuntimeLookup);
                if (directMethod == null && constrained.IsEnum)
                {
                    // Constrained calls to methods on enum methods resolve to System.Enum's methods. System.Enum is a reference
                    // type though, so we would fail to resolve and box. We have a special path for those to avoid boxing.
                    directMethod = _compilation.TypeSystemContext.TryResolveConstrainedEnumMethod(constrained, method);
                }

                if (directMethod != null)
                {
                    // Either
                    //    1. no constraint resolution at compile time (!directMethod)
                    // OR 2. no code sharing lookup in call
                    // OR 3. we have have resolved to an instantiating stub

                    methodAfterConstraintResolution = directMethod;

                    Debug.Assert(!methodAfterConstraintResolution.OwningType.IsInterface);
                    resolvedConstraint = true;

                    exactType = constrained;
                }
                else if (constrained.IsValueType)
                {
                    // We'll need to box `this`. Note we use _constrained here, because the other one is canonical.
                    AddBoxingDependencies(_constrained, reason);
                }
            }

            MethodDesc targetMethod = methodAfterConstraintResolution;

            bool exactContextNeedsRuntimeLookup;

            if (targetMethod.HasInstantiation)
            {
                exactContextNeedsRuntimeLookup = targetMethod.IsSharedByGenericInstantiations;
            }
            else
            {
                exactContextNeedsRuntimeLookup = exactType.IsCanonicalSubtype(CanonicalFormKind.Any);
            }

            //
            // Determine whether to perform direct call
            //

            bool directCall = false;

            if (targetMethod.Signature.IsStatic)
            {
                // Static methods are always direct calls
                directCall = true;
            }
            else if (targetMethod.OwningType.IsInterface)
            {
                // Force all interface calls to be interpreted as if they are virtual.
                directCall = false;
            }
            else if ((opcode != ILOpcode.callvirt && opcode != ILOpcode.ldvirtftn) || resolvedConstraint)
            {
                directCall = true;
            }
            else
            {
                if (!targetMethod.IsVirtual || targetMethod.IsFinal || targetMethod.OwningType.IsSealed())
                {
                    directCall = true;
                }
            }

            bool allowInstParam = opcode != ILOpcode.ldvirtftn && opcode != ILOpcode.ldftn;

            if (directCall && !allowInstParam && targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific).RequiresInstArg())
            {
                // Needs a single address to call this method but the method needs a hidden argument.
                // We need a fat function pointer for this that captures both things.

                if (exactContextNeedsRuntimeLookup)
                {
                    _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.MethodEntry, runtimeDeterminedMethod), reason);
                }
                else
                {
                    _dependencies.Add(_factory.FatFunctionPointer(runtimeDeterminedMethod), reason);
                }
            }
            else if (directCall)
            {
                bool referencingArrayAddressMethod = false;

                if (targetMethod.IsIntrinsic)
                {
                    // If this is an intrinsic method with a callsite-specific expansion, this will replace
                    // the method with a method the intrinsic expands into. If it's not the special intrinsic,
                    // method stays unchanged.
                    targetMethod = _compilation.ExpandIntrinsicForCallsite(targetMethod, _canonMethod);

                    // Array address method requires special dependency tracking.
                    referencingArrayAddressMethod = targetMethod.IsArrayAddressMethod();
                }

                MethodDesc concreteMethod = targetMethod;
                targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);

                if (targetMethod.IsConstructor && targetMethod.OwningType.IsString)
                {
                    _dependencies.Add(_factory.StringAllocator(targetMethod), reason);
                }
                else if (exactContextNeedsRuntimeLookup)
                {
                    if (targetMethod.IsSharedByGenericInstantiations && !resolvedConstraint && !referencingArrayAddressMethod)
                    {
                        ISymbolNode instParam = null;

                        if (targetMethod.RequiresInstMethodDescArg())
                        {
                            instParam = GetGenericLookupHelper(ReadyToRunHelperId.MethodDictionary, runtimeDeterminedMethod);
                        }
                        else if (targetMethod.RequiresInstMethodTableArg())
                        {
                            bool hasHiddenParameter = true;

                            if (targetMethod.IsIntrinsic)
                            {
                                if (_factory.TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(targetMethod))
                                {
                                    hasHiddenParameter = false;
                                }
                            }

                            if (hasHiddenParameter)
                            {
                                instParam = GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, runtimeDeterminedMethod.OwningType);
                            }
                        }

                        if (instParam != null)
                        {
                            _dependencies.Add(instParam, reason);
                        }

                        _dependencies.Add(_factory.CanonicalEntrypoint(targetMethod), reason);
                    }
                    else
                    {
                        Debug.Assert(!forceUseRuntimeLookup);
                        _dependencies.Add(_factory.MethodEntrypoint(targetMethod), reason);

                        if (targetMethod.RequiresInstMethodTableArg() && resolvedConstraint)
                        {
                            if (_constrained.IsRuntimeDeterminedSubtype)
                            {
                                _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, _constrained), reason);
                            }
                            else
                            {
                                _dependencies.Add(_factory.ConstructedTypeSymbol(_constrained), reason);
                            }
                        }

                        if (referencingArrayAddressMethod && !_isReadOnly)
                        {
                            // Address method is special - it expects an instantiation argument, unless a readonly prefix was applied.
                            _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, runtimeDeterminedMethod.OwningType), reason);
                        }
                    }
                }
                else
                {
                    ISymbolNode instParam = null;

                    if (targetMethod.RequiresInstMethodDescArg())
                    {
                        instParam = _compilation.NodeFactory.MethodGenericDictionary(concreteMethod);
                    }
                    else if (targetMethod.RequiresInstMethodTableArg() || (referencingArrayAddressMethod && !_isReadOnly))
                    {
                        // Ask for a constructed type symbol because we need the vtable to get to the dictionary
                        instParam = _compilation.NodeFactory.ConstructedTypeSymbol(concreteMethod.OwningType);
                    }

                    if (instParam != null)
                    {
                        _dependencies.Add(instParam, reason);
                    }

                    _dependencies.Add(_compilation.NodeFactory.MethodEntrypoint(targetMethod), reason);
                }
            }
            else if (method.HasInstantiation)
            {
                // Generic virtual method call

                if (exactContextNeedsRuntimeLookup)
                {
                    _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.MethodHandle, runtimeDeterminedMethod), reason);
                }
                else
                {
                    _dependencies.Add(_factory.RuntimeMethodHandle(runtimeDeterminedMethod), reason);
                }

                _dependencies.Add(GetHelperEntrypoint(ReadyToRunHelper.GVMLookupForSlot), reason);
            }
            else if (method.OwningType.IsInterface)
            {
                if (exactContextNeedsRuntimeLookup)
                {
                    _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.VirtualDispatchCell, runtimeDeterminedMethod), reason);
                }
                else
                {
                    _dependencies.Add(_factory.InterfaceDispatchCell(method), reason);
                }
            }
            else if (_compilation.HasFixedSlotVTable(method.OwningType))
            {
                // No dependencies: virtual call through the vtable
            }
            else
            {
                MethodDesc slotDefiningMethod = targetMethod.IsNewSlot ?
                                                targetMethod : MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(targetMethod);
                _dependencies.Add(_factory.VirtualMethodUse(slotDefiningMethod), reason);
            }
        }
Ejemplo n.º 6
0
 private ILToken NewToken(Object value, int tokenType)
 {
     Debug.Assert(value != null);
     _tokens.Add(value);
     return((ILToken)(_tokens.Count | tokenType));
 }
Ejemplo n.º 7
0
        public static MethodIL EmitIL(MethodDesc method)
        {
            Debug.Assert(method.OwningType.IsDelegate);
            Debug.Assert(method.OwningType.IsTypeDefinition);
            Debug.Assert(method.IsRuntimeImplemented);

            if (method.Name == "BeginInvoke" || method.Name == "EndInvoke")
            {
                // BeginInvoke and EndInvoke are not supported on .NET Core
                ILEmitter    emit       = new ILEmitter();
                ILCodeStream codeStream = emit.NewCodeStream();
                MethodDesc   notSupportedExceptionHelper = method.Context.GetHelperEntryPoint("ThrowHelpers", "ThrowPlatformNotSupportedException");
                codeStream.EmitCallThrowHelper(emit, notSupportedExceptionHelper);
                return(emit.Link(method));
            }

            if (method.Name == ".ctor")
            {
                // We only support delegate creation if the IL follows the delegate creation verifiability requirements
                // described in ECMA-335 III.4.21 (newobj – create a new object). The codegen is expected to
                // intrinsically expand the pattern.
                // If the delegate creation doesn't follow the pattern, we generate code that throws at runtime.
                // We could potentially implement this (unreliably) through the use of reflection metadata,
                // but it remains to be proven that this is an actual customer scenario.
                ILEmitter    emit       = new ILEmitter();
                ILCodeStream codeStream = emit.NewCodeStream();
                MethodDesc   notSupportedExceptionHelper = method.Context.GetHelperEntryPoint("ThrowHelpers", "ThrowPlatformNotSupportedException");
                codeStream.EmitCallThrowHelper(emit, notSupportedExceptionHelper);
                return(emit.Link(method));
            }

            if (method.Name == "Invoke")
            {
                TypeSystemContext context = method.Context;

                ILEmitter    emit                 = new ILEmitter();
                TypeDesc     delegateType         = context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType;
                FieldDesc    firstParameterField  = delegateType.GetKnownField("m_firstParameter");
                FieldDesc    functionPointerField = delegateType.GetKnownField("m_functionPointer");
                ILCodeStream codeStream           = emit.NewCodeStream();

                codeStream.EmitLdArg(0);
                codeStream.Emit(ILOpcode.ldfld, emit.NewToken(firstParameterField.InstantiateAsOpen()));
                for (int i = 0; i < method.Signature.Length; i++)
                {
                    codeStream.EmitLdArg(i + 1);
                }
                codeStream.EmitLdArg(0);
                codeStream.Emit(ILOpcode.ldfld, emit.NewToken(functionPointerField.InstantiateAsOpen()));

                MethodSignature signature = method.Signature;
                if (method.OwningType.HasInstantiation)
                {
                    // If the owning type is generic, the signature will contain T's and U's.
                    // We need !0's and !1's.
                    TypeDesc[] typesToReplace   = new TypeDesc[method.OwningType.Instantiation.Length];
                    TypeDesc[] replacementTypes = new TypeDesc[typesToReplace.Length];
                    for (int i = 0; i < typesToReplace.Length; i++)
                    {
                        typesToReplace[i]   = method.OwningType.Instantiation[i];
                        replacementTypes[i] = context.GetSignatureVariable(i, method: false);
                    }
                    TypeDesc[] parameters = new TypeDesc[method.Signature.Length];
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        parameters[i] = method.Signature[i].ReplaceTypesInConstructionOfType(typesToReplace, replacementTypes);
                    }
                    TypeDesc returnType = method.Signature.ReturnType.ReplaceTypesInConstructionOfType(typesToReplace, replacementTypes);
                    signature = new MethodSignature(signature.Flags, signature.GenericParameterCount, returnType, parameters);
                }

                codeStream.Emit(ILOpcode.calli, emit.NewToken(signature));

                codeStream.Emit(ILOpcode.ret);

                return(emit.Link(method));
            }

            return(null);
        }
Ejemplo n.º 8
0
 public override bool IsBlocked(MetadataType type)
 {
     Debug.Assert(type.IsTypeDefinition);
     return(true);
 }
Ejemplo n.º 9
0
 public override bool IsBlocked(MethodDesc method)
 {
     Debug.Assert(method.IsTypicalMethodDefinition);
     return(true);
 }
Ejemplo n.º 10
0
        private static                                 Marshaller[] InitializeMarshallers(MethodDesc targetMethod, InteropStateManager interopStateManager, PInvokeFlags flags)
        {
            MarshalDirection direction = MarshalDirection.Forward;
            MethodSignature  methodSig;

            switch (targetMethod)
            {
            case DelegateMarshallingMethodThunk delegateMethod:
                methodSig = delegateMethod.DelegateSignature;
                direction = delegateMethod.Direction;
                break;

            case CalliMarshallingMethodThunk calliMethod:
                methodSig = calliMethod.TargetSignature;
                break;

            default:
                methodSig = targetMethod.Signature;
                break;
            }
            int indexOffset = 0;

            if (!methodSig.IsStatic && direction == MarshalDirection.Forward)
            {
                // For instance methods(eg. Forward delegate marshalling thunk), first argument is
                // the instance
                indexOffset = 1;
            }
            ParameterMetadata[] parameterMetadataArray = targetMethod.GetParameterMetadata();
            Marshaller[]        marshallers            = new Marshaller[methodSig.Length + 1];
            int parameterIndex = 0;
            ParameterMetadata parameterMetadata;

            for (int i = 0; i < marshallers.Length; i++)
            {
                Debug.Assert(parameterIndex == parameterMetadataArray.Length || i <= parameterMetadataArray[parameterIndex].Index);
                if (parameterIndex == parameterMetadataArray.Length || i < parameterMetadataArray[parameterIndex].Index)
                {
                    // if we don't have metadata for the parameter, create a dummy one
                    parameterMetadata = new ParameterMetadata(i, ParameterMetadataAttributes.None, null);
                }
                else
                {
                    Debug.Assert(i == parameterMetadataArray[parameterIndex].Index);
                    parameterMetadata = parameterMetadataArray[parameterIndex++];
                }
                TypeDesc parameterType = (i == 0) ? methodSig.ReturnType : methodSig[i - 1];  //first item is the return type
                marshallers[i] = Marshaller.CreateMarshaller(parameterType,
                                                             MarshallerType.Argument,
                                                             parameterMetadata.MarshalAsDescriptor,
                                                             direction,
                                                             marshallers,
                                                             interopStateManager,
                                                             indexOffset + parameterMetadata.Index,
                                                             flags,
                                                             parameterMetadata.In,
                                                             parameterMetadata.Out,
                                                             parameterMetadata.Return
                                                             );
            }

            return(marshallers);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Is there a reflection invoke stub for a method that is invokable?
 /// </summary>
 public override bool HasReflectionInvokeStubForInvokableMethod(MethodDesc method)
 {
     Debug.Assert(IsReflectionInvokable(method));
     return(false);
 }
Ejemplo n.º 12
0
        private void EmitDelegateCall(DelegateMarshallingMethodThunk delegateMethod, PInvokeILCodeStreams ilCodeStreams)
        {
            ILEmitter         emitter                 = ilCodeStreams.Emitter;
            ILCodeStream      fnptrLoadStream         = ilCodeStreams.FunctionPointerLoadStream;
            ILCodeStream      marshallingCodeStream   = ilCodeStreams.MarshallingCodeStream;
            ILCodeStream      callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream;
            TypeSystemContext context                 = _targetMethod.Context;

            Debug.Assert(delegateMethod != null);

            if (delegateMethod.Kind == DelegateMarshallingMethodThunkKind.ReverseOpenStatic)
            {
                //
                // For Open static delegates call
                //     InteropHelpers.GetCurrentCalleeOpenStaticDelegateFunctionPointer()
                // which returns a function pointer. Just call the function pointer and we are done.
                //
                TypeDesc[] parameters = new TypeDesc[_marshallers.Length - 1];
                for (int i = 1; i < _marshallers.Length; i++)
                {
                    parameters[i - 1] = _marshallers[i].ManagedParameterType;
                }

                MethodSignature managedSignature = new MethodSignature(
                    MethodSignatureFlags.Static, 0, _marshallers[0].ManagedParameterType, parameters);

                fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(
                                         delegateMethod.Context.GetHelperType("InteropHelpers").GetKnownMethod(
                                             "GetCurrentCalleeOpenStaticDelegateFunctionPointer", null)));

                ILLocalVariable vDelegateStub = emitter.NewLocal(
                    delegateMethod.Context.GetWellKnownType(WellKnownType.IntPtr));

                fnptrLoadStream.EmitStLoc(vDelegateStub);
                callsiteSetupCodeStream.EmitLdLoc(vDelegateStub);
                callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(managedSignature));
            }
            else if (delegateMethod.Kind == DelegateMarshallingMethodThunkKind.ReverseClosed)
            {
                //
                // For closed delegates call
                //     InteropHelpers.GetCurrentCalleeDelegate<Delegate>
                // which returns the delegate. Do a CallVirt on the invoke method.
                //
                MethodDesc instantiatedHelper = delegateMethod.Context.GetInstantiatedMethod(
                    delegateMethod.Context.GetHelperType("InteropHelpers")
                    .GetKnownMethod("GetCurrentCalleeDelegate", null),
                    new Instantiation((delegateMethod.DelegateType)));

                fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(instantiatedHelper));

                ILLocalVariable vDelegateStub = emitter.NewLocal(delegateMethod.DelegateType);
                fnptrLoadStream.EmitStLoc(vDelegateStub);
                marshallingCodeStream.EmitLdLoc(vDelegateStub);
                MethodDesc invokeMethod = delegateMethod.DelegateType.GetKnownMethod("Invoke", null);
                callsiteSetupCodeStream.Emit(ILOpcode.callvirt, emitter.NewToken(invokeMethod));
            }
            else if (delegateMethod.Kind == DelegateMarshallingMethodThunkKind
                     .ForwardNativeFunctionWrapper)
            {
                // if the SetLastError flag is set in UnmanagedFunctionPointerAttribute, clear the error code before doing P/Invoke
                if (_flags.SetLastError)
                {
                    callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                     InteropTypes.GetPInvokeMarshal(context).GetKnownMethod("ClearLastWin32Error", null)));
                }

                //
                // For NativeFunctionWrapper we need to load the native function and call it
                //
                fnptrLoadStream.EmitLdArg(0);
                fnptrLoadStream.Emit(ILOpcode.call, emitter.NewToken(InteropTypes
                                                                     .GetNativeFunctionPointerWrapper(context)
                                                                     .GetMethod("get_NativeFunctionPointer", null)));

                var fnPtr = emitter.NewLocal(
                    context.GetWellKnownType(WellKnownType.IntPtr));

                fnptrLoadStream.EmitStLoc(fnPtr);
                callsiteSetupCodeStream.EmitLdLoc(fnPtr);

                TypeDesc   nativeReturnType     = _marshallers[0].NativeParameterType;
                TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1];

                for (int i = 1; i < _marshallers.Length; i++)
                {
                    nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType;
                }

                MethodSignature nativeSig = new MethodSignature(
                    MethodSignatureFlags.Static | _flags.UnmanagedCallingConvention, 0, nativeReturnType, nativeParameterTypes);

                callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig));

                // if the SetLastError flag is set in UnmanagedFunctionPointerAttribute, call the PInvokeMarshal.
                // SaveLastWin32Error so that last error can be used later by calling
                // PInvokeMarshal.GetLastWin32Error
                if (_flags.SetLastError)
                {
                    callsiteSetupCodeStream.Emit(ILOpcode.call, emitter.NewToken(
                                                     InteropTypes.GetPInvokeMarshal(context)
                                                     .GetKnownMethod("SaveLastWin32Error", null)));
                }
            }
            else
            {
                Debug.Fail("Unexpected DelegateMarshallingMethodThunkKind");
            }
        }
Ejemplo n.º 13
0
        public override bool IsBlocked(MethodDesc method)
        {
            Debug.Assert(method.IsTypicalMethodDefinition);

            var ecmaMethod = method as EcmaMethod;

            if (ecmaMethod == null)
            {
                return(true);
            }

            ModuleBlockingMode moduleBlockingMode = _blockedModules.GetOrCreateValue(ecmaMethod.Module).BlockingMode;

            if (moduleBlockingMode == ModuleBlockingMode.None)
            {
                return(false);
            }
            else if (moduleBlockingMode == ModuleBlockingMode.FullyBlocked)
            {
                return(true);
            }

            // We are blocking internal implementation details
            Debug.Assert(moduleBlockingMode == ModuleBlockingMode.BlockedInternals);

            var owningType = (EcmaType)ecmaMethod.OwningType;

            if (_blockedTypes.GetOrCreateValue(owningType).IsBlocked)
            {
                return(true);
            }

            MethodAttributes accessibility = ecmaMethod.Attributes & MethodAttributes.Public;

            if (accessibility != MethodAttributes.Family &&
                accessibility != MethodAttributes.FamORAssem &&
                accessibility != MethodAttributes.Public)
            {
                // Non-public and non-protected methods should be blocked, but binary serialization
                // forces us to exclude a couple things if the type is serializable.
                if (owningType.IsSerializable)
                {
                    MethodSignature signature = ecmaMethod.Signature;

                    if (ecmaMethod.IsConstructor &&
                        signature.Length == 2 &&
                        signature[0] == SerializationInfoType
                        /* && ecmaMethod.Signature[1] is StreamingContext */)
                    {
                        return(false);
                    }

                    // Methods with these attributes can be called during serialization
                    if (signature.Length == 1 && !signature.IsStatic && signature.ReturnType.IsVoid &&
                        (ecmaMethod.HasCustomAttribute("System.Runtime.Serialization", "OnSerializingAttribute") ||
                         ecmaMethod.HasCustomAttribute("System.Runtime.Serialization", "OnSerializedAttribute") ||
                         ecmaMethod.HasCustomAttribute("System.Runtime.Serialization", "OnDeserializingAttribute") ||
                         ecmaMethod.HasCustomAttribute("System.Runtime.Serialization", "OnDeserializedAttribute")))
                    {
                        return(false);
                    }
                }

                return(true);
            }

            // Methods on Array`1<T> are implementation details that implement the generic interfaces on
            // arrays. They should not generate metadata or be reflection invokable.
            // We could get rid of this special casing two ways:
            // * Make these method stop being regular EcmaMethods with Array<T> as their owning type, or
            // * Make these methods implement the interfaces explicitly (they would become private and naturally blocked)
            if (ecmaMethod.OwningType == ArrayOfTType)
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 14
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            if (LastNonConfigurationInstance != null)
            {
                //bug in Mono for Android or whatever: after config change the extra fields are wrong
                // -> reload:
                Reload();
                return;
            }

            _appTask = AppTask.GetTaskInOnCreate(savedInstanceState, Intent);

            SetContentView(Resource.Layout.entry_edit);
            _closeForReload = false;

            // Likely the app has been killed exit the activity
            if (!App.Kp2a.DatabaseIsUnlocked)
            {
                Finish();
                return;
            }


            if (Intent.GetBooleanExtra(IntentContinueWithEditing, false))
            {
                //property "State" will return the state
            }
            else
            {
                Database db = App.Kp2a.GetDb();

                App.Kp2a.EntryEditActivityState = new EntryEditActivityState();
                ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
                State.ShowPassword = !prefs.GetBoolean(GetString(Resource.String.maskpass_key), Resources.GetBoolean(Resource.Boolean.maskpass_default));

                Intent i         = Intent;
                String uuidBytes = i.GetStringExtra(KeyEntry);

                PwUuid entryId = PwUuid.Zero;
                if (uuidBytes != null)
                {
                    entryId = new PwUuid(MemUtil.HexStringToByteArray(uuidBytes));
                }

                State.ParentGroup = null;
                if (entryId.Equals(PwUuid.Zero))
                {
                    //creating new entry
                    String groupId = i.GetStringExtra(KeyParent);
                    State.ParentGroup = db.KpDatabase.RootGroup.FindGroup(new PwUuid(MemUtil.HexStringToByteArray(groupId)), true);

                    PwUuid  templateId    = new PwUuid(MemUtil.HexStringToByteArray(i.GetStringExtra(KeyTemplateUuid)));
                    PwEntry templateEntry = null;
                    if (!PwUuid.Zero.Equals(templateId))
                    {
                        templateEntry = db.Entries[templateId];
                    }

                    if (KpEntryTemplatedEdit.IsTemplate(templateEntry))
                    {
                        CreateNewFromKpEntryTemplate(db, templateEntry);
                    }
                    else if (templateEntry != null)
                    {
                        CreateNewFromStandardTemplate(templateEntry);
                    }
                    else
                    {
                        CreateNewWithoutTemplate(db);
                    }

                    _appTask.PrepareNewEntry(State.EntryInDatabase);
                    State.IsNew         = true;
                    State.EntryModified = true;
                }
                else
                {
                    Debug.Assert(entryId != null);

                    State.EntryInDatabase = db.Entries [entryId];
                    State.IsNew           = false;
                }

                State.Entry = State.EntryInDatabase.CloneDeep();
                if (KpEntryTemplatedEdit.IsTemplated(db, State.Entry))
                {
                    State.EditMode = new KpEntryTemplatedEdit(db, State.Entry);
                }
                else
                {
                    State.EditMode = new DefaultEdit();
                }
            }

            if (!State.EntryModified)
            {
                SetResult(KeePass.ExitNormal);
            }
            else
            {
                SetResult(KeePass.ExitRefreshTitle);
            }



            FillData();
            View scrollView = FindViewById(Resource.Id.entry_scroll);

            scrollView.ScrollBarStyle = ScrollbarStyles.InsideInset;

            ImageButton iconButton = (ImageButton)FindViewById(Resource.Id.icon_button);

            if (State.SelectedIcon)
            {
                App.Kp2a.GetDb().DrawableFactory.AssignDrawableTo(iconButton, this, App.Kp2a.GetDb().KpDatabase, (PwIcon)State.SelectedIconId, State.SelectedCustomIconId, false);
            }
            iconButton.Click += (sender, evt) => {
                UpdateEntryFromUi(State.Entry);
                IconPickerActivity.Launch(this);
            };


            // Generate password button
            FindViewById(Resource.Id.generate_button).Click += (sender, e) =>
            {
                UpdateEntryFromUi(State.Entry);
                GeneratePasswordActivity.Launch(this);
            };



            // Save button
            //SupportActionBar.SetCustomView(Resource.Layout.SaveButton);

            if (State.IsNew)
            {
                SupportActionBar.Title = GetString(Resource.String.add_entry);
            }
            else
            {
                SupportActionBar.Title = GetString(Resource.String.edit_entry);
            }

            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);

            // Respect mask password setting
            MakePasswordVisibleOrHidden();

            ImageButton btnTogglePassword = (ImageButton)FindViewById(Resource.Id.toggle_password);

            btnTogglePassword.Click += (sender, e) =>
            {
                State.ShowPassword = !State.ShowPassword;
                MakePasswordVisibleOrHidden();
            };
            PorterDuff.Mode mMode = PorterDuff.Mode.SrcAtop;
            Color           color = new Color(189, 189, 189);

            btnTogglePassword.SetColorFilter(color, mMode);


            Button addButton = (Button)FindViewById(Resource.Id.add_advanced);

            addButton.Visibility = ViewStates.Visible;
            addButton.Click     += (sender, e) =>
            {
                LinearLayout container = (LinearLayout)FindViewById(Resource.Id.advanced_container);

                KeyValuePair <string, ProtectedString> pair = new KeyValuePair <string, ProtectedString>("", new ProtectedString(true, ""));
                View ees = CreateExtraStringView(pair);
                container.AddView(ees);

                State.EntryModified = true;

                /*TextView keyView = (TextView) ees.FindViewById(Resource.Id.title);
                 * keyView.RequestFocus();*/
                EditAdvancedString(ees.FindViewById(Resource.Id.edit_extra));
            };
            SetAddExtraStringEnabled();

            ((CheckBox)FindViewById(Resource.Id.entry_expires_checkbox)).CheckedChange += (sender, e) =>
            {
                State.Entry.Expires = e.IsChecked;
                if (e.IsChecked)
                {
                    if (State.Entry.ExpiryTime < DateTime.Now)
                    {
                        State.Entry.ExpiryTime = DateTime.Now;
                    }
                }
                UpdateExpires();
                State.EntryModified = true;
            };
        }
Ejemplo n.º 15
0
 public void EndHandler(ILExceptionRegionBuilder builder)
 {
     Debug.Assert(builder._endHandlerStream == null);
     builder._endHandlerStream = this;
     builder._endHandlerOffset = _length;
 }
Ejemplo n.º 16
0
 public override bool IsBlocked(FieldDesc field)
 {
     Debug.Assert(field.IsTypicalFieldDefinition);
     return(true);
 }
Ejemplo n.º 17
0
 internal void Place(ILCodeStream codeStream, int offsetWithinCodeStream)
 {
     Debug.Assert(!IsPlaced);
     _codeStream             = codeStream;
     _offsetWithinCodeStream = offsetWithinCodeStream;
 }
Ejemplo n.º 18
0
 protected virtual void OutputGCDesc(ref ObjectDataBuilder builder)
 {
     // Non-constructed EETypeNodes get no GC Desc
     Debug.Assert(GCDescSize == 0);
 }
Ejemplo n.º 19
0
        public MethodIL Link(MethodDesc owningMethod)
        {
            int totalLength       = 0;
            int numSequencePoints = 0;

            for (int i = 0; i < _codeStreams.Count; i++)
            {
                ILCodeStream ilCodeStream = _codeStreams[i];
                ilCodeStream._startOffsetForLinking = totalLength;
                totalLength       += ilCodeStream._length;
                numSequencePoints += ilCodeStream._sequencePoints.Count;
            }

            byte[] ilInstructions = new byte[totalLength];
            int    copiedLength   = 0;

            for (int i = 0; i < _codeStreams.Count; i++)
            {
                ILCodeStream ilCodeStream = _codeStreams[i];
                ilCodeStream.PatchLabels();
                Array.Copy(ilCodeStream._instructions, 0, ilInstructions, copiedLength, ilCodeStream._length);
                copiedLength += ilCodeStream._length;
            }

            MethodDebugInformation debugInfo = null;

            if (numSequencePoints > 0)
            {
                ILSequencePoint[] sequencePoints = new ILSequencePoint[numSequencePoints];
                int copiedSequencePointLength    = 0;
                for (int codeStreamIndex = 0; codeStreamIndex < _codeStreams.Count; codeStreamIndex++)
                {
                    ILCodeStream ilCodeStream = _codeStreams[codeStreamIndex];

                    for (int sequencePointIndex = 0; sequencePointIndex < ilCodeStream._sequencePoints.Count; sequencePointIndex++)
                    {
                        ILSequencePoint sequencePoint = ilCodeStream._sequencePoints[sequencePointIndex];
                        sequencePoints[copiedSequencePointLength] = new ILSequencePoint(
                            ilCodeStream._startOffsetForLinking + sequencePoint.Offset,
                            sequencePoint.Document,
                            sequencePoint.LineNumber);
                        copiedSequencePointLength++;
                    }
                }

                debugInfo = new EmittedMethodDebugInformation(sequencePoints);
            }

            ILExceptionRegion[] exceptionRegions = null;

            int numberOfExceptionRegions = _finallyRegions.Count;

            if (numberOfExceptionRegions > 0)
            {
                exceptionRegions = new ILExceptionRegion[numberOfExceptionRegions];

                for (int i = 0; i < _finallyRegions.Count; i++)
                {
                    ILExceptionRegionBuilder region = _finallyRegions[i];

                    Debug.Assert(region.IsDefined);

                    exceptionRegions[i] = new ILExceptionRegion(ILExceptionRegionKind.Finally,
                                                                region.TryOffset, region.TryLength, region.HandlerOffset, region.HandlerLength,
                                                                classToken: 0, filterOffset: 0);
                }
            }

            var result = new ILStubMethodIL(owningMethod, ilInstructions, _locals.ToArray(), _tokens.ToArray(), exceptionRegions, debugInfo);

            result.CheckStackBalance();
            return(result);
        }
Ejemplo n.º 20
0
        protected virtual void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType, bool relocsOnly)
        {
            Debug.Assert(EmitVirtualSlotsAndInterfaces);

            declType = declType.GetClosestDefType();

            var baseType = declType.BaseType;

            if (baseType != null)
            {
                OutputVirtualSlots(factory, ref objData, implType, baseType, relocsOnly);
            }

            // The generic dictionary pointer occupies the first slot of each type vtable slice
            if (declType.HasGenericDictionarySlot())
            {
                // All generic interface types have a dictionary slot, but only some of them have an actual dictionary.
                bool isInterfaceWithAnEmptySlot = declType.IsInterface &&
                                                  declType.ConvertToCanonForm(CanonicalFormKind.Specific) == declType;

                // Note: Canonical type instantiations always have a generic dictionary vtable slot, but it's empty
                if (declType.IsCanonicalSubtype(CanonicalFormKind.Any) ||
                    factory.LazyGenericsPolicy.UsesLazyGenerics(declType) ||
                    isInterfaceWithAnEmptySlot)
                {
                    objData.EmitZeroPointer();
                }
                else
                {
                    objData.EmitPointerReloc(factory.TypeGenericDictionary(declType));
                }
            }

            // It's only okay to touch the actual list of slots if we're in the final emission phase
            // or the vtable is not built lazily.
            if (relocsOnly && !factory.CompilationModuleGroup.ShouldProduceFullVTable(declType))
            {
                return;
            }

            // Actual vtable slots follow
            IReadOnlyList <MethodDesc> virtualSlots = factory.VTable(declType).Slots;

            for (int i = 0; i < virtualSlots.Count; i++)
            {
                MethodDesc declMethod = virtualSlots[i];

                // No generic virtual methods can appear in the vtable!
                Debug.Assert(!declMethod.HasInstantiation);

                MethodDesc implMethod = implType.GetClosestDefType().FindVirtualFunctionTargetMethodOnObjectType(declMethod);

                if (!implMethod.IsAbstract)
                {
                    MethodDesc canonImplMethod = implMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
                    objData.EmitPointerReloc(factory.MethodEntrypoint(canonImplMethod, implMethod.OwningType.IsValueType));
                }
                else
                {
                    objData.EmitZeroPointer();
                }
            }
        }
        protected override void ProcessRecord()
        {
            List <PSRepositoryInfo> items = new List <PSRepositoryInfo>();

            switch (ParameterSetName)
            {
            case NameParameterSet:
                if (!Utils.TryCreateValidUri(uriString: Uri,
                                             cmdletPassedIn: this,
                                             uriResult: out _uri,
                                             errorRecord: out ErrorRecord errorRecord))
                {
                    ThrowTerminatingError(errorRecord);
                }

                try
                {
                    items.Add(RepositorySettings.AddRepository(Name, _uri, Priority, Trusted, CredentialInfo, Force, this, out string errorMsg));

                    if (!string.IsNullOrEmpty(errorMsg))
                    {
                        ThrowTerminatingError(new ErrorRecord(
                                                  new PSInvalidOperationException(errorMsg),
                                                  "ErrorInNameParameterSet",
                                                  ErrorCategory.InvalidArgument,
                                                  this));
                    }
                }
                catch (Exception e)
                {
                    ThrowTerminatingError(new ErrorRecord(
                                              new PSInvalidOperationException(e.Message),
                                              "ErrorInNameParameterSet",
                                              ErrorCategory.InvalidArgument,
                                              this));
                }
                break;

            case PSGalleryParameterSet:
                try
                {
                    items.Add(PSGalleryParameterSetHelper(Priority, Trusted));
                }
                catch (Exception e)
                {
                    ThrowTerminatingError(new ErrorRecord(
                                              new PSInvalidOperationException(e.Message),
                                              "ErrorInPSGalleryParameterSet",
                                              ErrorCategory.InvalidArgument,
                                              this));
                }
                break;

            case RepositoriesParameterSet:
                try
                {
                    items = RepositoriesParameterSetHelper();
                }
                catch (Exception e)
                {
                    ThrowTerminatingError(new ErrorRecord(
                                              new PSInvalidOperationException(e.Message),
                                              "ErrorInRepositoriesParameterSet",
                                              ErrorCategory.InvalidArgument,
                                              this));
                }
                break;

            default:
                Dbg.Assert(false, "Invalid parameter set");
                break;
            }

            if (PassThru)
            {
                foreach (PSRepositoryInfo repo in items)
                {
                    WriteObject(repo);
                }
            }
        }
Ejemplo n.º 22
0
        private void EmitILForAccessor()
        {
            Debug.Assert(!_method.OwningType.IsSzArray);

            var codeStream = _emitter.NewCodeStream();
            var context    = _method.Context;

            var int32Type = context.GetWellKnownType(WellKnownType.Int32);

            var totalLocalNum  = _emitter.NewLocal(int32Type);
            var lengthLocalNum = _emitter.NewLocal(int32Type);

            int pointerSize = context.Target.PointerSize;

            var         rangeExceptionLabel        = _emitter.NewCodeLabel();
            ILCodeLabel typeMismatchExceptionLabel = null;

            if (!_elementType.IsValueType)
            {
                // Type check
                if (_method.Kind == ArrayMethodKind.Set)
                {
                    MethodDesc checkArrayStore =
                        context.SystemModule.GetKnownType("System.Runtime", "RuntimeImports").GetKnownMethod("RhCheckArrayStore", null);

                    codeStream.EmitLdArg(0);
                    codeStream.EmitLdArg(_rank + 1);

                    codeStream.Emit(ILOpcode.call, _emitter.NewToken(checkArrayStore));
                }
                else if (_method.Kind == ArrayMethodKind.Address)
                {
                    TypeDesc objectType    = context.GetWellKnownType(WellKnownType.Object);
                    TypeDesc eetypePtrType = context.SystemModule.GetKnownType("System", "EETypePtr");

                    MethodDesc eetypePtrOfMethod = eetypePtrType.GetKnownMethod("EETypePtrOf", null)
                                                   .MakeInstantiatedMethod(new Instantiation(new[] { _elementType }));

                    typeMismatchExceptionLabel = _emitter.NewCodeLabel();

                    ILLocalVariable thisEEType = _emitter.NewLocal(eetypePtrType);

                    // EETypePtr actualElementType = this.EETypePtr.ArrayElementType;
                    codeStream.EmitLdArg(0);
                    codeStream.Emit(ILOpcode.call, _emitter.NewToken(objectType.GetKnownMethod("get_EETypePtr", null)));
                    codeStream.EmitStLoc(thisEEType);
                    codeStream.EmitLdLoca(thisEEType);
                    codeStream.Emit(ILOpcode.call,
                                    _emitter.NewToken(eetypePtrType.GetKnownMethod("get_ArrayElementType", null)));

                    // EETypePtr expectedElementType = EETypePtr.EETypePtrOf<_elementType>();
                    codeStream.Emit(ILOpcode.call, _emitter.NewToken(eetypePtrOfMethod));

                    // if (expectedElementType != actualElementType)
                    //     ThrowHelpers.ThrowArrayTypeMismatchException();
                    codeStream.Emit(ILOpcode.call, _emitter.NewToken(eetypePtrType.GetKnownMethod("op_Equality", null)));
                    codeStream.Emit(ILOpcode.brfalse, typeMismatchExceptionLabel);
                }
            }

            for (int i = 0; i < _rank; i++)
            {
                // The first two fields are EEType pointer and total length. Lengths for each dimension follows.
                int lengthOffset = (2 * pointerSize + i * int32Type.GetElementSize());

                EmitLoadInteriorAddress(codeStream, lengthOffset);
                codeStream.Emit(ILOpcode.ldind_i4);
                codeStream.EmitStLoc(lengthLocalNum);

                codeStream.EmitLdArg(i + 1);

                // Compare with length
                codeStream.Emit(ILOpcode.dup);
                codeStream.EmitLdLoc(lengthLocalNum);
                codeStream.Emit(ILOpcode.bge_un, rangeExceptionLabel);

                // Add to the running total if we have one already
                if (i > 0)
                {
                    codeStream.EmitLdLoc(totalLocalNum);
                    codeStream.EmitLdLoc(lengthLocalNum);
                    codeStream.Emit(ILOpcode.mul);
                    codeStream.Emit(ILOpcode.add);
                }
                codeStream.EmitStLoc(totalLocalNum);
            }

            // Compute element offset
            // TODO: This leaves unused space for lower bounds to match CoreCLR...
            int firstElementOffset = (2 * pointerSize + 2 * _rank * int32Type.GetElementSize());

            EmitLoadInteriorAddress(codeStream, firstElementOffset);

            codeStream.EmitLdLoc(totalLocalNum);

            int elementSize = _elementType.GetElementSize();

            if (elementSize != 1)
            {
                codeStream.EmitLdc(elementSize);
                codeStream.Emit(ILOpcode.mul);
            }
            codeStream.Emit(ILOpcode.add);

            switch (_method.Kind)
            {
            case ArrayMethodKind.Get:
                codeStream.Emit(ILOpcode.ldobj, _emitter.NewToken(_elementType));
                break;

            case ArrayMethodKind.Set:
                codeStream.EmitLdArg(_rank + 1);
                codeStream.Emit(ILOpcode.stobj, _emitter.NewToken(_elementType));
                break;

            case ArrayMethodKind.Address:
                break;
            }

            codeStream.Emit(ILOpcode.ret);

            codeStream.EmitLdc(0);
            codeStream.EmitLabel(rangeExceptionLabel); // Assumes that there is one "int" pushed on the stack
            codeStream.Emit(ILOpcode.pop);

            MethodDesc throwHelper = context.GetHelperEntryPoint("ThrowHelpers", "ThrowIndexOutOfRangeException");

            codeStream.EmitCallThrowHelper(_emitter, throwHelper);

            if (typeMismatchExceptionLabel != null)
            {
                codeStream.EmitLabel(typeMismatchExceptionLabel);
                codeStream.EmitCallThrowHelper(_emitter, context.GetHelperEntryPoint("ThrowHelpers", "ThrowArrayTypeMismatchException"));
            }
        }
Ejemplo n.º 23
0
 internal static bool ObjectHasComponentSize(object obj)
 {
     Debug.Assert(obj != null);
     return(obj.EETypePtr.ComponentSize != 0);
 }
Ejemplo n.º 24
0
        public AnalysisBasedMetadataManager(
            CompilerTypeSystemContext typeSystemContext,
            MetadataBlockingPolicy blockingPolicy,
            ManifestResourceBlockingPolicy resourceBlockingPolicy,
            string logFile,
            StackTraceEmissionPolicy stackTracePolicy,
            DynamicInvokeThunkGenerationPolicy invokeThunkGenerationPolicy,
            IEnumerable <ModuleDesc> modulesWithMetadata,
            IEnumerable <ReflectableEntity <TypeDesc> > reflectableTypes,
            IEnumerable <ReflectableEntity <MethodDesc> > reflectableMethods,
            IEnumerable <ReflectableEntity <FieldDesc> > reflectableFields,
            IEnumerable <TypeDesc> ldtokenReferenceableTypes)
            : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy, invokeThunkGenerationPolicy)
        {
            _modulesWithMetadata = new List <ModuleDesc>(modulesWithMetadata);

            foreach (var refType in reflectableTypes)
            {
                _reflectableTypes.Add(refType.Entity, refType.Category);
            }

            foreach (var refMethod in reflectableMethods)
            {
                // Asking for description or runtime mapping for a member without asking
                // for the owning type would mean we can't actually satisfy the request.
                Debug.Assert((refMethod.Category & MetadataCategory.Description) == 0 ||
                             (_reflectableTypes[refMethod.Entity.OwningType] & MetadataCategory.Description) != 0);
                Debug.Assert((refMethod.Category & MetadataCategory.RuntimeMapping) == 0 ||
                             (_reflectableTypes[refMethod.Entity.OwningType] & MetadataCategory.RuntimeMapping) != 0);
                _reflectableMethods.Add(refMethod.Entity, refMethod.Category);
            }

            foreach (var refField in reflectableFields)
            {
                // Asking for description or runtime mapping for a member without asking
                // for the owning type would mean we can't actually satisfy the request.
                Debug.Assert((refField.Category & MetadataCategory.Description) == 0 ||
                             (_reflectableTypes[refField.Entity.OwningType] & MetadataCategory.Description) != 0);
                Debug.Assert((refField.Category & MetadataCategory.RuntimeMapping) == 0 ||
                             (_reflectableTypes[refField.Entity.OwningType] & MetadataCategory.RuntimeMapping) != 0);
                _reflectableFields.Add(refField.Entity, refField.Category);
            }

            _ldtokenReferenceableTypes = new HashSet <TypeDesc>(ldtokenReferenceableTypes);

#if DEBUG
            HashSet <ModuleDesc> moduleHash = new HashSet <ModuleDesc>(_modulesWithMetadata);
            foreach (var refType in reflectableTypes)
            {
                // The instantiated types need to agree on the Description bit with the definition.
                // GetMetadataCategory relies on that.
                Debug.Assert((GetMetadataCategory(refType.Entity.GetTypeDefinition()) & MetadataCategory.Description)
                             == (GetMetadataCategory(refType.Entity) & MetadataCategory.Description));

                Debug.Assert(!(refType.Entity is MetadataType) || moduleHash.Contains(((MetadataType)refType.Entity).Module));
            }

            foreach (var refMethod in reflectableMethods)
            {
                // The instantiated methods need to agree on the Description bit with the definition.
                // GetMetadataCategory relies on that.
                Debug.Assert((GetMetadataCategory(refMethod.Entity.GetTypicalMethodDefinition()) & MetadataCategory.Description)
                             == (GetMetadataCategory(refMethod.Entity) & MetadataCategory.Description));

                // Canonical form of the method needs to agree with the logical form
                Debug.Assert(GetMetadataCategory(refMethod.Entity) == GetMetadataCategory(refMethod.Entity.GetCanonMethodTarget(CanonicalFormKind.Specific)));
            }

            foreach (var refField in reflectableFields)
            {
                // The instantiated fields need to agree on the Description bit with the definition.
                // GetMetadataCategory relies on that.
                Debug.Assert((GetMetadataCategory(refField.Entity.GetTypicalFieldDefinition()) & MetadataCategory.Description)
                             == (GetMetadataCategory(refField.Entity) & MetadataCategory.Description));
            }
#endif
        }
Ejemplo n.º 25
0
        private void ImportLdToken(int token)
        {
            object obj = _methodIL.GetObject(token);

            if (obj is TypeDesc)
            {
                var type = (TypeDesc)obj;

                if (type.IsRuntimeDeterminedSubtype)
                {
                    _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, type), "ldtoken");
                }
                else
                {
                    _dependencies.Add(_factory.MaximallyConstructableType(type), "ldtoken");
                }

                // If this is a ldtoken Type / GetValueInternal sequence, we're done.
                BasicBlock nextBasicBlock = _basicBlocks[_currentOffset];
                if (nextBasicBlock == null)
                {
                    if ((ILOpcode)_ilBytes[_currentOffset] == ILOpcode.call)
                    {
                        int methodToken = ReadILTokenAt(_currentOffset + 1);
                        var method      = (MethodDesc)_methodIL.GetObject(methodToken);
                        if (IsRuntimeTypeHandleGetValueInternal(method))
                        {
                            // Codegen expands this and doesn't do the normal ldtoken.
                            return;
                        }
                    }
                }

                _dependencies.Add(GetHelperEntrypoint(ReadyToRunHelper.GetRuntimeTypeHandle), "ldtoken");
            }
            else if (obj is MethodDesc)
            {
                var method = (MethodDesc)obj;
                if (method.IsRuntimeDeterminedExactMethod)
                {
                    _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.MethodHandle, method), "ldtoken");
                }
                else
                {
                    _dependencies.Add(_factory.RuntimeMethodHandle(method), "ldtoken");
                }

                _dependencies.Add(GetHelperEntrypoint(ReadyToRunHelper.GetRuntimeMethodHandle), "ldtoken");
            }
            else
            {
                Debug.Assert(obj is FieldDesc);

                // First check if this is a ldtoken Field / InitializeArray sequence.
                BasicBlock nextBasicBlock = _basicBlocks[_currentOffset];
                if (nextBasicBlock == null)
                {
                    if ((ILOpcode)_ilBytes[_currentOffset] == ILOpcode.call)
                    {
                        int methodToken = ReadILTokenAt(_currentOffset + 1);
                        var method      = (MethodDesc)_methodIL.GetObject(methodToken);
                        if (IsRuntimeHelpersInitializeArray(method))
                        {
                            // Codegen expands this and doesn't do the normal ldtoken.
                            return;
                        }
                    }
                }

                var field = (FieldDesc)obj;
                if (field.OwningType.IsRuntimeDeterminedSubtype)
                {
                    _dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.FieldHandle, field), "ldtoken");
                }
                else
                {
                    _dependencies.Add(_factory.RuntimeFieldHandle(field), "ldtoken");
                }

                _dependencies.Add(GetHelperEntrypoint(ReadyToRunHelper.GetRuntimeFieldHandle), "ldtoken");
            }
        }
Ejemplo n.º 26
0
 internal int RelativeToAbsoluteOffset(int relativeOffset)
 {
     Debug.Assert(_startOffsetForLinking != StartOffsetNotSet);
     return(_startOffsetForLinking + relativeOffset);
 }
Ejemplo n.º 27
0
        public RemoteSessionHyperVSocketServer(bool LoopbackMode)
        {
            // TODO: uncomment below code when .NET supports Hyper-V socket duplication

            /*
             * NamedPipeClientStream clientPipeStream;
             * byte[] buffer = new byte[1000];
             * int bytesRead;
             */
            _syncObject = new object();

            Exception ex = null;

            try
            {
                // TODO: uncomment below code when .NET supports Hyper-V socket duplication

                /*
                 * if (!LoopbackMode)
                 * {
                 *  //
                 *  // Create named pipe client.
                 *  //
                 *  using (clientPipeStream = new NamedPipeClientStream(".",
                 *                                                      "PS_VMSession",
                 *                                                      PipeDirection.InOut,
                 *                                                      PipeOptions.None,
                 *                                                      TokenImpersonationLevel.None))
                 *  {
                 *      //
                 *      // Connect to named pipe server.
                 *      //
                 *      clientPipeStream.Connect(10*1000);
                 *
                 *      //
                 *      // Read LPWSAPROTOCOL_INFO.
                 *      //
                 *      bytesRead = clientPipeStream.Read(buffer, 0, 1000);
                 *  }
                 * }
                 *
                 * //
                 * // Create duplicate socket.
                 * //
                 * byte[] protocolInfo = new byte[bytesRead];
                 * Array.Copy(buffer, protocolInfo, bytesRead);
                 *
                 * SocketInformation sockInfo = new SocketInformation();
                 * sockInfo.ProtocolInformation = protocolInfo;
                 * sockInfo.Options = SocketInformationOptions.Connected;
                 *
                 * socket = new Socket(sockInfo);
                 * if (socket == null)
                 * {
                 *  Dbg.Assert(false, "Unexpected error in RemoteSessionHyperVSocketServer.");
                 *
                 *  tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty,
                 *      "Unexpected error in constructor: {0}", "socket duplication failure");
                 * }
                 */

                // TODO: remove below 6 lines of code when .NET supports Hyper-V socket duplication
                Guid serviceId = new Guid("a5201c21-2770-4c11-a68e-f182edb29220"); // HV_GUID_VM_SESSION_SERVICE_ID_2
                HyperVSocketEndPoint endpoint = new HyperVSocketEndPoint(HyperVSocketEndPoint.AF_HYPERV, Guid.Empty, serviceId);

                Socket listenSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, (System.Net.Sockets.ProtocolType) 1);
                listenSocket.Bind(endpoint);

                listenSocket.Listen(1);
                HyperVSocket = listenSocket.Accept();

                Stream = new NetworkStream(HyperVSocket, true);

                // Create reader/writer streams.
                TextReader           = new StreamReader(Stream);
                TextWriter           = new StreamWriter(Stream);
                TextWriter.AutoFlush = true;

                //
                // listenSocket is not closed when it goes out of scope here. Sometimes it is
                // closed later in this thread, while other times it is not closed at all. This will
                // cause problem when we set up a second PowerShell Direct session. Let's
                // explicitly close listenSocket here for safe.
                //
                if (listenSocket != null)
                {
                    try { listenSocket.Dispose(); }
                    catch (ObjectDisposedException) { }
                }
            }
            catch (Exception e)
            {
                ex = e;
            }

            if (ex != null)
            {
                Dbg.Assert(false, "Unexpected error in RemoteSessionHyperVSocketServer.");

                // Unexpected error.
                string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
                _tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty,
                                     "Unexpected error in constructor: {0}", errorMessage);

                throw new PSInvalidOperationException(
                          PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteSessionHyperVSocketServerConstructorFailure),
                          ex,
                          PSRemotingErrorId.RemoteSessionHyperVSocketServerConstructorFailure.ToString(),
                          ErrorCategory.InvalidOperation,
                          null);
            }
        }
Ejemplo n.º 28
0
 public void BeginTry(ILExceptionRegionBuilder builder)
 {
     Debug.Assert(builder._beginTryStream == null);
     builder._beginTryStream = this;
     builder._beginTryOffset = _length;
 }
 public StringIterator(string s, int index)
 {
     Debug.Assert(index <= s.Length);
     _string = s;
     _index  = index;
 }
Ejemplo n.º 30
0
        // Compare two sets of generic type parameters to see if they're assignment compatible taking generic
        // variance into account. It's assumed they've already had their type definition matched (which
        // implies their arities are the same as well). The fForceCovariance argument tells the method to
        // override the defined variance of each parameter and instead assume it is covariant. This is used to
        // implement covariant array interfaces.
        static bool TypeParametersAreCompatible(Type[] pSourceInstantiation,
                                                Type[] pTargetInstantiation,
                                                Type[] pVarianceInfo,
                                                bool fForceCovariance)
        {
            // The types represent different instantiations of the same generic type. The
            // arity of both had better be the same.
            Debug.Assert(pSourceInstantiation.Length == pTargetInstantiation.Length, "arity mismatch betweeen generic instantiations");

            Debug.Assert(fForceCovariance || pTargetInstantiation.Length == pVarianceInfo.Length, "arity mismatch betweeen generic instantiations");

            // Walk through the instantiations comparing the cast compatibility of each pair
            // of type args.
            for (int i = 0; i < pTargetInstantiation.Length; i++)
            {
                TypeInfo pTargetArgType = pTargetInstantiation[i].GetTypeInfo();
                TypeInfo pSourceArgType = pSourceInstantiation[i].GetTypeInfo();

                GenericParameterAttributes varType;
                if (fForceCovariance)
                {
                    varType = GenericParameterAttributes.Covariant;
                }
                else
                {
                    varType = pVarianceInfo[i].GetTypeInfo().GenericParameterAttributes & GenericParameterAttributes.VarianceMask;
                }

                switch (varType)
                {
                case GenericParameterAttributes.None:
                    // Non-variant type params need to be identical.

                    if (!AreTypesEquivalentInternal(pSourceArgType, pTargetArgType))
                    {
                        return(false);
                    }

                    break;

                case GenericParameterAttributes.Covariant:
                    // For covariance (or out type params in C#) the object must implement an
                    // interface with a more derived type arg than the target interface. Or
                    // the object interface can have a type arg that is an interface
                    // implemented by the target type arg.
                    // For instance:
                    //   class Foo : ICovariant<String> is ICovariant<Object>
                    //   class Foo : ICovariant<Bar> is ICovariant<IBar>
                    //   class Foo : ICovariant<IBar> is ICovariant<Object>

                    if (!AreTypesAssignableInternal(pSourceArgType, pTargetArgType, false, false))
                    {
                        return(false);
                    }

                    break;

                case GenericParameterAttributes.Contravariant:
                    // For contravariance (or in type params in C#) the object must implement
                    // an interface with a less derived type arg than the target interface. Or
                    // the object interface can have a type arg that is a class implementing
                    // the interface that is the target type arg.
                    // For instance:
                    //   class Foo : IContravariant<Object> is IContravariant<String>
                    //   class Foo : IContravariant<IBar> is IContravariant<Bar>
                    //   class Foo : IContravariant<Object> is IContravariant<IBar>

                    if (!AreTypesAssignableInternal(pTargetArgType, pSourceArgType, false, false))
                    {
                        return(false);
                    }

                    break;

                default:
                    Debug.Assert(false, "unknown generic variance type");
                    return(false);
                }
            }

            return(true);
        }