Esempio n. 1
0
        public Assembly LoadFromNativeImagePath(string nativeImagePath, string?assemblyPath)
        {
            if (nativeImagePath == null)
            {
                throw new ArgumentNullException(nameof(nativeImagePath));
            }

            if (PathInternal.IsPartiallyQualified(nativeImagePath))
            {
                throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, nativeImagePath), nameof(nativeImagePath));
            }

            if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
            {
                throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, assemblyPath), nameof(assemblyPath));
            }

            lock (_unloadLock)
            {
                VerifyIsAlive();

                return(InternalLoadFromPath(assemblyPath, nativeImagePath));
            }
        }
Esempio n. 2
0
        public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath)
        {
            if (nativeImagePath == null)
            {
                throw new ArgumentNullException(nameof(nativeImagePath));
            }

            if (PathInternal.IsPartiallyQualified(nativeImagePath))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(nativeImagePath));
            }

            if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath));
            }

            // Basic validation has succeeded - lets try to load the NI image.
            // Ask LoadFile to load the specified assembly in the DefaultContext
            RuntimeAssembly loadedAssembly = null;

            LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
            return(loadedAssembly);
        }
Esempio n. 3
0
        protected void CreateList()
        {
            String[] expressionsArray = Split(m_expressions);

            m_list = new ArrayList();

            for (int index = 0; index < expressionsArray.Length; ++index)
            {
                if (expressionsArray[index] != null && !expressionsArray[index].Equals(""))
                {
                    String temp = ProcessSingleString(expressionsArray[index]);

                    int indexOfNull = temp.IndexOf('\0');

                    if (indexOfNull != -1)
                    {
                        temp = temp.Substring(0, indexOfNull);
                    }

                    if (temp != null && !temp.Equals(""))
                    {
                        if (m_throwOnRelative)
                        {
                            if (PathInternal.IsPartiallyQualified(temp))
                            {
                                throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"));
                            }

                            temp = CanonicalizePath(temp);
                        }

                        m_list.Add(temp);
                    }
                }
            }
        }
Esempio n. 4
0
        internal static ArrayList CreateListFromExpressions(string[] str, bool needFullPath)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }
            ArrayList arrayList = new ArrayList();

            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == null)
                {
                    throw new ArgumentNullException("str");
                }
                string text = StringExpressionSet.StaticProcessWholeString(str[i]);
                if (text != null && text.Length != 0)
                {
                    string text2 = StringExpressionSet.StaticProcessSingleString(text);
                    int    num   = text2.IndexOf('\0');
                    if (num != -1)
                    {
                        text2 = text2.Substring(0, num);
                    }
                    if (text2 != null && text2.Length != 0)
                    {
                        if (PathInternal.IsPartiallyQualified(text2))
                        {
                            throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"));
                        }
                        text2 = StringExpressionSet.CanonicalizePath(text2, needFullPath);
                        arrayList.Add(text2);
                    }
                }
            }
            return(arrayList);
        }
Esempio n. 5
0
        // Load the specified assembly, and call the specified type's
        // "static void Initialize()" method.
        private static void CallStartupHook(string assemblyPath)
        {
            Debug.Assert(!String.IsNullOrEmpty(assemblyPath));
            Debug.Assert(!PathInternal.IsPartiallyQualified(assemblyPath));

            Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);

            Debug.Assert(assembly != null);
            Type type = assembly.GetType(StartupHookTypeName, throwOnError: true);

            // Look for a static method without any parameters
            MethodInfo initializeMethod = type.GetMethod(InitializeMethodName,
                                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
                                                         null,            // use default binder
                                                         Type.EmptyTypes, // parameters
                                                         null);           // no parameter modifiers

            bool wrongSignature = false;

            if (initializeMethod == null)
            {
                // There weren't any static methods without
                // parameters. Look for any methods with the correct
                // name, to provide precise error handling.
                try
                {
                    // This could find zero, one, or multiple methods
                    // with the correct name.
                    initializeMethod = type.GetMethod(InitializeMethodName,
                                                      BindingFlags.Public | BindingFlags.NonPublic |
                                                      BindingFlags.Static | BindingFlags.Instance);
                }
                catch (AmbiguousMatchException)
                {
                    // Found multiple
                    Debug.Assert(initializeMethod == null);
                    wrongSignature = true;
                }
                if (initializeMethod != null)
                {
                    // Found one
                    wrongSignature = true;
                }
                else
                {
                    // Didn't find any
                    throw new MissingMethodException(StartupHookTypeName, InitializeMethodName);
                }
            }
            else if (initializeMethod.ReturnType != typeof(void))
            {
                wrongSignature = true;
            }

            if (wrongSignature)
            {
                throw new ArgumentException(SR.Format(SR.Argument_InvalidStartupHookSignature,
                                                      StartupHookTypeName + Type.Delimiter + InitializeMethodName,
                                                      assemblyPath));
            }

            Debug.Assert(initializeMethod != null &&
                         initializeMethod.IsStatic &&
                         initializeMethod.ReturnType == typeof(void) &&
                         initializeMethod.GetParameters().Length == 0);

            initializeMethod.Invoke(null, null);
        }
Esempio n. 6
0
 public static bool IsPathFullyQualified(ReadOnlySpan <char> path)
 {
     return(!PathInternal.IsPartiallyQualified(path));
 }
Esempio n. 7
0
        } // PrepareDataForSetup

        private static object Setup(object arg)
        {
            var args           = (object[])arg;
            var friendlyName   = (string)args[0];
            var setup          = (AppDomainSetup)args[1];
            var propertyNames  = (string[])args[2]; // can contain null elements
            var propertyValues = (string[])args[3]; // can contain null elements

            AppDomain ad       = CurrentDomain;
            var       newSetup = new AppDomainSetup(setup, copyDomainBoundData: false);

            if (propertyNames != null && propertyValues != null)
            {
                for (int i = 0; i < propertyNames.Length; i++)
                {
                    // We want to set native dll probing directories before any P/Invokes have a
                    // chance to fire. The Path class, for one, has P/Invokes.
                    if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES")
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
                        }

                        string paths = propertyValues[i];
                        if (paths.Length == 0)
                        {
                            break;
                        }

                        nSetNativeDllSearchDirectories(paths);
                    }
                }

                for (int i = 0; i < propertyNames.Length; i++)
                {
                    if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("APPBASE");
                        }

                        if (PathInternal.IsPartiallyQualified(propertyValues[i]))
                        {
                            throw new ArgumentException(SR.Argument_AbsolutePathRequired);
                        }

                        newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
                    }
                    else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" ||
                             propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" ||
                             propertyNames[i] == "APP_PATHS" ||
                             propertyNames[i] == "APP_NI_PATHS")
                    {
                        string values = propertyValues[i];
                        if (values == null)
                        {
                            throw new ArgumentNullException(propertyNames[i]);
                        }

                        ad.SetData(propertyNames[i], NormalizeAppPaths(values));
                    }
                    else if (propertyNames[i] != null)
                    {
                        ad.SetData(propertyNames[i], propertyValues[i]);     // just propagate
                    }
                }
            }

            ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup

            // technically, we don't need this, newSetup refers to the same object as FusionStore
            // but it's confusing since it isn't immediately obvious whether we have a ref or a copy
            AppDomainSetup adSetup = ad.FusionStore;

            // set up the friendly name
            ad.nSetupFriendlyName(friendlyName);

            ad.CreateAppDomainManager(); // could modify FusionStore's object

            return(null);
        }
Esempio n. 8
0
        /// <summary>
        /// Gets reparse point information associated to <paramref name="linkPath"/>.
        /// </summary>
        /// <returns>The immediate link target, absolute or relative or null if the file is not a supported link.</returns>
        internal static unsafe string?GetImmediateLinkTarget(string linkPath, bool isDirectory, bool throwOnError, bool returnFullPath)
        {
            using SafeFileHandle handle = OpenSafeFileHandle(linkPath,
                                                             Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS |
                                                             Interop.Kernel32.FileOperations.FILE_FLAG_OPEN_REPARSE_POINT);

            if (handle.IsInvalid)
            {
                if (!throwOnError)
                {
                    return(null);
                }

                int error = Marshal.GetLastWin32Error();
                // File not found doesn't make much sense coming from a directory.
                if (isDirectory && error == Interop.Errors.ERROR_FILE_NOT_FOUND)
                {
                    error = Interop.Errors.ERROR_PATH_NOT_FOUND;
                }

                throw Win32Marshal.GetExceptionForWin32Error(error, linkPath);
            }

            byte[] buffer = ArrayPool <byte> .Shared.Rent(Interop.Kernel32.MAXIMUM_REPARSE_DATA_BUFFER_SIZE);

            try
            {
                bool success = Interop.Kernel32.DeviceIoControl(
                    handle,
                    dwIoControlCode: Interop.Kernel32.FSCTL_GET_REPARSE_POINT,
                    lpInBuffer: IntPtr.Zero,
                    nInBufferSize: 0,
                    lpOutBuffer: buffer,
                    nOutBufferSize: Interop.Kernel32.MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
                    out _,
                    IntPtr.Zero);

                if (!success)
                {
                    if (!throwOnError)
                    {
                        return(null);
                    }

                    int error = Marshal.GetLastWin32Error();
                    // The file or directory is not a reparse point.
                    if (error == Interop.Errors.ERROR_NOT_A_REPARSE_POINT)
                    {
                        return(null);
                    }

                    throw Win32Marshal.GetExceptionForWin32Error(error, linkPath);
                }

                Span <byte> bufferSpan = new(buffer);
                success = MemoryMarshal.TryRead(bufferSpan, out Interop.Kernel32.SymbolicLinkReparseBuffer rbSymlink);
                Debug.Assert(success);

                // We always use SubstituteName(Offset|Length) instead of PrintName(Offset|Length),
                // the latter is just the display name of the reparse point and it can show something completely unrelated to the target.

                if (rbSymlink.ReparseTag == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_SYMLINK)
                {
                    int offset = sizeof(Interop.Kernel32.SymbolicLinkReparseBuffer) + rbSymlink.SubstituteNameOffset;
                    int length = rbSymlink.SubstituteNameLength;

                    Span <char> targetPath = MemoryMarshal.Cast <byte, char>(bufferSpan.Slice(offset, length));

                    bool isRelative = (rbSymlink.Flags & Interop.Kernel32.SYMLINK_FLAG_RELATIVE) != 0;
                    if (!isRelative)
                    {
                        // Absolute target is in NT format and we need to clean it up before return it to the user.
                        if (targetPath.StartsWith(PathInternal.UncNTPathPrefix.AsSpan()))
                        {
                            // We need to prepend the Win32 equivalent of UNC NT prefix.
                            return(Path.Join(PathInternal.UncPathPrefix.AsSpan(), targetPath.Slice(PathInternal.UncNTPathPrefix.Length)));
                        }

                        return(GetTargetPathWithoutNTPrefix(targetPath));
                    }
                    else if (returnFullPath)
                    {
                        return(Path.Join(Path.GetDirectoryName(linkPath.AsSpan()), targetPath));
                    }
                    else
                    {
                        return(targetPath.ToString());
                    }
                }
                else if (rbSymlink.ReparseTag == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT)
                {
                    success = MemoryMarshal.TryRead(bufferSpan, out Interop.Kernel32.MountPointReparseBuffer rbMountPoint);
                    Debug.Assert(success);

                    int offset = sizeof(Interop.Kernel32.MountPointReparseBuffer) + rbMountPoint.SubstituteNameOffset;
                    int length = rbMountPoint.SubstituteNameLength;

                    Span <char> targetPath = MemoryMarshal.Cast <byte, char>(bufferSpan.Slice(offset, length));

                    // Unlike symbolic links, mount point paths cannot be relative.
                    Debug.Assert(!PathInternal.IsPartiallyQualified(targetPath));
                    // Mount points cannot point to a remote location.
                    Debug.Assert(!targetPath.StartsWith(PathInternal.UncNTPathPrefix.AsSpan()));
                    return(GetTargetPathWithoutNTPrefix(targetPath));
                }

                return(null);
            }
            finally
            {
                ArrayPool <byte> .Shared.Return(buffer);
            }
Esempio n. 9
0
        } // PrepareDataForSetup

        private static Object Setup(Object arg)
        {
            Contract.Requires(arg != null && arg is Object[]);
            Contract.Requires(((Object[])arg).Length >= 8);

            Object[]       args                     = (Object[])arg;
            String         friendlyName             = (String)args[0];
            AppDomainSetup setup                    = (AppDomainSetup)args[1];
            IntPtr         parentSecurityDescriptor = (IntPtr)args[2];
            bool           generateDefaultEvidence  = (bool)args[3];

            byte[] serializedEvidence = (byte[])args[4];
            AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5];
            string sandboxName = (string)args[6];

            string[] propertyNames  = (string[])args[7]; // can contain null elements
            string[] propertyValues = (string[])args[8]; // can contain null elements
            // extract evidence
            Evidence providedSecurityInfo = null;
            Evidence creatorsSecurityInfo = null;

            AppDomain      ad       = AppDomain.CurrentDomain;
            AppDomainSetup newSetup = new AppDomainSetup(setup, false);

            if (propertyNames != null && propertyValues != null)
            {
                for (int i = 0; i < propertyNames.Length; i++)
                {
                    // We want to set native dll probing directories before any P/Invokes have a
                    // chance to fire. The Path class, for one, has P/Invokes.
                    if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES")
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
                        }

                        string paths = propertyValues[i];
                        if (paths.Length == 0)
                        {
                            break;
                        }

                        nSetNativeDllSearchDirectories(paths);
                    }
                }

                for (int i = 0; i < propertyNames.Length; i++)
                {
                    if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("APPBASE");
                        }

                        if (PathInternal.IsPartiallyQualified(propertyValues[i]))
                        {
                            throw new ArgumentException(SR.Argument_AbsolutePathRequired);
                        }

                        newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
                    }
                    else if (propertyNames[i] == "LOADER_OPTIMIZATION")
                    {
                        if (propertyValues[i] == null)
                        {
                            throw new ArgumentNullException("LOADER_OPTIMIZATION");
                        }

                        switch (propertyValues[i])
                        {
                        case "SingleDomain": newSetup.LoaderOptimization = LoaderOptimization.SingleDomain; break;

                        case "MultiDomain": newSetup.LoaderOptimization = LoaderOptimization.MultiDomain; break;

                        case "MultiDomainHost": newSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost; break;

                        case "NotSpecified": newSetup.LoaderOptimization = LoaderOptimization.NotSpecified; break;

                        default: throw new ArgumentException(SR.Argument_UnrecognizedLoaderOptimization, "LOADER_OPTIMIZATION");
                        }
                    }
                    else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" ||
                             propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" ||
                             propertyNames[i] == "APP_PATHS" ||
                             propertyNames[i] == "APP_NI_PATHS")
                    {
                        string values = propertyValues[i];
                        if (values == null)
                        {
                            throw new ArgumentNullException(propertyNames[i]);
                        }

                        ad.SetData(propertyNames[i], NormalizeAppPaths(values));
                    }
                    else if (propertyNames[i] != null)
                    {
                        ad.SetData(propertyNames[i], propertyValues[i]);     // just propagate
                    }
                }
            }

            ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup

            // technically, we don't need this, newSetup refers to the same object as FusionStore
            // but it's confusing since it isn't immediately obvious whether we have a ref or a copy
            AppDomainSetup adSetup = ad.FusionStore;

            adSetup.InternalSetApplicationTrust(sandboxName);

            // set up the friendly name
            ad.nSetupFriendlyName(friendlyName);

#if FEATURE_COMINTEROP
            if (setup != null && setup.SandboxInterop)
            {
                ad.nSetDisableInterfaceCache();
            }
#endif // FEATURE_COMINTEROP

            ad.CreateAppDomainManager(); // could modify FusionStore's object
            ad.InitializeDomainSecurity(providedSecurityInfo,
                                        creatorsSecurityInfo,
                                        generateDefaultEvidence,
                                        parentSecurityDescriptor,
                                        true);

            // can load user code now
            if (initializerInfo != null)
            {
                adSetup.AppDomainInitializer = initializerInfo.Unwrap();
            }
            RunInitializer(adSetup);

            return(null);
        }
Esempio n. 10
0
 public void IsPartiallyQualifiedTest(string path, bool expected)
 {
     Assert.Equal(expected, PathInternal.IsPartiallyQualified(path));
 }
Esempio n. 11
0
        public void AddExpressions(String str)
        {
            if (str == null)
            {
                throw new ArgumentNullException(nameof(str));
            }
            Contract.EndContractBlock();
            if (str.Length == 0)
            {
                return;
            }

            str = ProcessWholeString(str);

            if (m_expressions == null)
            {
                m_expressions = str;
            }
            else
            {
                m_expressions = m_expressions + m_separators[0] + str;
            }

            m_expressionsArray = null;

            // We have to parse the string and compute the list here.
            // The logic in this class tries to delay this parsing but
            // since operations like IsSubsetOf are called during
            // demand evaluation, it is not safe to delay this step
            // as that would cause concurring threads to update the object
            // at the same time. The CheckList operation should ideally be
            // removed from this class, but for the sake of keeping the
            // changes to a minimum here, we simply make sure m_list
            // cannot be null by parsing m_expressions eagerly.

            String[] arystr = Split(str);

            if (m_list == null)
            {
                m_list = new ArrayList();
            }

            for (int index = 0; index < arystr.Length; ++index)
            {
                if (arystr[index] != null && !arystr[index].Equals(""))
                {
                    String temp        = ProcessSingleString(arystr[index]);
                    int    indexOfNull = temp.IndexOf('\0');

                    if (indexOfNull != -1)
                    {
                        temp = temp.Substring(0, indexOfNull);
                    }

                    if (temp != null && !temp.Equals(""))
                    {
                        if (m_throwOnRelative)
                        {
                            if (PathInternal.IsPartiallyQualified(temp))
                            {
                                throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"));
                            }

                            temp = CanonicalizePath(temp);
                        }

                        m_list.Add(temp);
                    }
                }
            }

            Reduce();
        }