예제 #1
0
 public static IntPtr LoadProcedure(SafeLibraryHandle libHandle, string functionName)
 {
     IntPtr functionNamePtr = Marshal.StringToHGlobalAnsi(functionName);
     IntPtr procHandle = dlsym(libHandle, functionNamePtr);
     Marshal.FreeHGlobal(functionNamePtr);
     return procHandle;
 }
예제 #2
0
        private string GetString(int resourceId, SafeLibraryHandle moduleHandle)
        {
            StringBuilder stringBuilder = new StringBuilder();
            int           num           = NativeMethods.LoadString(moduleHandle, resourceId, stringBuilder, 0);

            if (num != 0)
            {
                stringBuilder.EnsureCapacity(num + 1);
                NativeMethods.LoadString(moduleHandle, resourceId, stringBuilder, stringBuilder.Capacity);
            }
            return(stringBuilder.ToString());
        }
예제 #3
0
        public ResourceFile(string filename) : this()
        {
            if (filename == null)
            {
                throw new ArgumentNullException(nameof(filename));
            }

            using (var hm = new SafeLibraryHandle(filename))
                FileName = GetModuleFileName(hm);
            hLib = new SafeLibraryHandle(filename,
                                         LoadLibraryExFlags.LOAD_LIBRARY_AS_DATAFILE | LoadLibraryExFlags.LOAD_LIBRARY_AS_IMAGE_RESOURCE);
        }
예제 #4
0
    /// <summary>
    /// Opens a library. If 'filename' is not a fully-qualified path, the default search path is used.
    /// </summary>
    public static SafeLibraryHandle Open(string filename)
    {
        const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800U; // from libloaderapi.h

        SafeLibraryHandle handle = UnsafeNativeMethods.LoadLibraryEx(filename, IntPtr.Zero, LOAD_LIBRARY_SEARCH_SYSTEM32);

        if (handle == null || handle.IsInvalid)
        {
            UnsafeNativeMethods.ThrowExceptionForLastWin32Error();
        }
        return(handle);
    }
예제 #5
0
        private string GetCaption(int id)
        {
            if (user32 == null)
            {
                user32 = UnsafeNativeMethods.LoadLibrary(Environment.SystemDirectory + "\\User32.dll");
            }

            var sb = new StringBuilder(256);

            UnsafeNativeMethods.LoadString(user32, (uint)id, sb, sb.Capacity);
            return(sb.ToString().Replace("&", ""));
        }
        private bool InitFromFile(string path, Guid clsid)
        {
            using (SafeLibraryHandle lib = COMUtilities.SafeLoadLibrary(path))
            {
                IntPtr pInfo = FindProxyDllInfo(lib, clsid);
                if (pInfo == IntPtr.Zero)
                {
                    return(false);
                }

                return(InitFromFileInfo(pInfo));
            }
        }
예제 #7
0
 private unsafe void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, SafeLibraryHandle libHandle)
 {
     if (value != (IntPtr)0)
     {
         // call DsReplicaFreeInfo
         var dsReplicaFreeInfo = (delegate * unmanaged <int, IntPtr, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaFreeInfo");
         if (dsReplicaFreeInfo == null)
         {
             throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
         }
         dsReplicaFreeInfo((int)type, value);
     }
 }
예제 #8
0
 public void EnumResourceNamesTest()
 {
     using (var hLib = new SafeLibraryHandle(@"C:\Windows\System32\en-US\aclui.dll.mui", LoadLibraryExFlags.LOAD_LIBRARY_AS_IMAGE_RESOURCE))
     {
         var l = EnumResourceNamesEx(hLib, ResourceType.RT_STRING);
         Assert.That(l.Count, Is.GreaterThan(0));
         foreach (var resourceName in l)
         {
             LoadString(hLib, resourceName, out IntPtr sptr, 0);
             TestContext.WriteLine($"{resourceName} = {StringHelper.GetString(sptr)}");
         }
     }
 }
예제 #9
0
                                /*
                                 * HELPER FUNCTIONS
                                 */
                                private static SafeLibraryHandle GetLibHandle(string libraryName, ref SafeLibraryHandle?safeLibraryHandle)
    {
        if (safeLibraryHandle is null)
        {
            var newHandle = SafeLibraryHandle.Open(libraryName);
            if (Interlocked.CompareExchange(ref safeLibraryHandle, newHandle, null) is not null)
            {
                newHandle.Dispose();
            }
        }

        return(safeLibraryHandle);
    }
예제 #10
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (!disposed)
            {
                disposed = true;

                if (handle != null && !handle.IsClosed)
                {
                    handle.Dispose();
                    handle = null;
                }
            }
        }
예제 #11
0
 /// <summary>
 /// Constructor to load a dll and be responible for freeing it.
 /// </summary>
 /// <param name="fileName">full path name of dll to load</param>
 /// <exception cref="System.IO.FileNotFoundException">if fileName can't be found</exception>
 /// <remarks>Throws exceptions on failure. Most common failure would be file-not-found, or
 /// that the file is not a  loadable image.</remarks>
 public UnmanagedLibrary(string fileName)
 {
     _libraryHandle = NativeMethods.LoadLibrary(fileName);
     if (_libraryHandle.IsInvalid)
     {
         try {
             var hr = Marshal.GetHRForLastWin32Error();
             Marshal.ThrowExceptionForHR(hr);
         } catch (Exception e) {
             throw new Exception(string.Format("Error loading library \"{0}\"", fileName), e);
         }
     }
 }
예제 #12
0
 public SevenZipFormat(string sevenZipLibPath)
 {
     this.LibHandle = LoadLibrary(sevenZipLibPath);
     if (this.LibHandle.IsInvalid)
     {
         throw new Win32Exception();
     }
     if (GetProcAddress(this.LibHandle, "GetHandlerProperty") == IntPtr.Zero)
     {
         this.LibHandle.Close();
         throw new ArgumentException();
     }
 }
예제 #13
0
        public byte[] GetDiskStream(SafeLibraryHandle hInst, int partId, int stateId, int propId)
        {
            var r = GetThemeStream(hTheme, partId, stateId, propId, out byte[] bytes, out int bLen, hInst);

            if (r.Succeeded)
            {
                return(bytes);
            }
            if (r != 0x80070490)
            {
                throw new InvalidOperationException("Bad GetThemeStream");
            }
            return(null);
        }
예제 #14
0
        public static void CheckPlatformSupport()
        {
            bool isPlatformSupported = false;

            using (SafeLibraryHandle libHandle = Interop.mincore.LoadLibraryExW(Interop.Libraries.WinHttp, IntPtr.Zero, 0))
            {
                isPlatformSupported = Interop.mincore.GetProcAddress(libHandle, WebSocketAvailableApiCheck) != IntPtr.Zero;
            }

            if (!isPlatformSupported)
            {
                WebSocketValidate.ThrowPlatformNotSupportedException();
            }
        }
예제 #15
0
        /// <summary>
        /// Load the specified executable file or DLL, and get ready to extract the icons.
        /// </summary>
        /// <param name="filename">The name of a file from which icons will be extracted.</param>
        public IconExtractor(string filename)
        {
            if (filename == null)
            {
                throw new ArgumentNullException(nameof(filename));
            }

            using (var hm = new SafeLibraryHandle(filename))
                FileName = GetModuleFileName(hm);
            hModule = new SafeLibraryHandle(filename,
                                            LoadLibraryExFlags.LOAD_LIBRARY_AS_DATAFILE | LoadLibraryExFlags.LOAD_LIBRARY_AS_IMAGE_RESOURCE);
            resInfo   = EnumResourceNames(hModule, ResourceTypes.GroupIcon);
            iconCache = new Icon[IconCount];
        }
예제 #16
0
        public void FormatMessageTest()
        {
            var s = FormatMessage(Win32Error.ERROR_INVALID_PARAMETER);

            Assert.That(s, Is.Not.Null);
            TestContext.WriteLine(s);

            using (var hLib = new SafeLibraryHandle(@"wininet.dll", LoadLibraryExFlags.LOAD_LIBRARY_AS_DATAFILE))
            {
                s = FormatMessage(12175, new[] { "Fred", "Alice" }, hLib);
                Assert.That(s, Is.Not.Null);
                TestContext.WriteLine(s);
            }
        }
예제 #17
0
        private static bool GetAddrInfoExSupportsOverlapped()
        {
            using (SafeLibraryHandle libHandle = Interop.Kernel32.LoadLibraryExW(Interop.Libraries.Ws2_32, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_SEARCH_SYSTEM32))
            {
                if (libHandle.IsInvalid)
                {
                    return(false);
                }

                // We can't just check that 'GetAddrInfoEx' exists, because it existed before supporting overlapped.
                // The existance of 'GetAddrInfoExCancel' indicates that overlapped is supported.
                return(Interop.Kernel32.GetProcAddress(libHandle, Interop.Winsock.GetAddrInfoExCancelFunctionName) != IntPtr.Zero);
            }
        }
예제 #18
0
 public void LoadResourceTest()
 {
     using (var hlib = new SafeLibraryHandle("ole32.dll", LoadLibraryExFlags.LOAD_LIBRARY_AS_DATAFILE))
     {
         var hres = FindResource(hlib, new SafeResourceId(4), new SafeResourceId(ResourceType.RT_CURSOR));
         Assert.That(hres, Is.Not.EqualTo(IntPtr.Zero));
         var sz = SizeofResource(hlib, hres);
         Assert.That(sz, Is.GreaterThan(0));
         var pres = LoadResource(hlib, hres);
         Assert.That(pres, Is.Not.EqualTo(IntPtr.Zero));
         var pmem = LockResource(pres);
         Assert.That(pmem, Is.Not.EqualTo(IntPtr.Zero));
     }
 }
        private static SafeLibraryHandle ExtractAndLoadEmbededResource(string relativePath)
        {
            var assembly = typeof(AEngine).Assembly;
            var resource = EmbededResourceHelper.FindByName(assembly, relativePath);

            if (resource != null)
            {
                string tempFolderPath = GetTempFolderPath();
                var    output_file    = Path.Combine(tempFolderPath, relativePath);
                EmbededResourceHelper.ExtractToFile(assembly, resource, output_file);
                return(SafeLibraryHandle.LoadLibrary(output_file));
            }

            return(null);
        }
예제 #20
0
        private void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, SafeLibraryHandle libHandle)
        {
            if (value != (IntPtr)0)
            {
                // call DsReplicaFreeInfo
                IntPtr functionPtr = global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaFreeInfo");
                if (functionPtr == (IntPtr)0)
                {
                    throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
                }
                UnsafeNativeMethods.DsReplicaFreeInfo dsReplicaFreeInfo = (UnsafeNativeMethods.DsReplicaFreeInfo)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsReplicaFreeInfo));

                dsReplicaFreeInfo((int)type, value);
            }
        }
예제 #21
0
            internal UnmanagedLibrary(string libraryName, SafeLibraryHandle libraryHandle)
            {
                if (string.IsNullOrWhiteSpace(libraryName))
                {
                    throw new ArgumentException("A valid library name is expected.", "libraryName");
                }
                if (libraryHandle.IsNullOrInvalid())
                {
                    throw new ArgumentNullException("libraryHandle");
                }

                TraceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);

                _handle = libraryHandle;
            }
        static WebSocketProtocolComponent()
        {
            s_webSocketDllHandle = Interop.Kernel32.LoadLibraryExW(Interop.Libraries.WebSocket, IntPtr.Zero, 0);

            if (!s_webSocketDllHandle.IsInvalid)
            {
                s_supportedVersion = GetSupportedVersion();

                s_ServerFakeRequestHeaders = new Interop.WebSocket.HttpHeader[]
                {
                    new Interop.WebSocket.HttpHeader()
                    {
                        Name        = HttpKnownHeaderNames.Connection,
                        NameLength  = (uint)HttpKnownHeaderNames.Connection.Length,
                        Value       = HttpKnownHeaderNames.Upgrade,
                        ValueLength = (uint)HttpKnownHeaderNames.Upgrade.Length
                    },
                    new Interop.WebSocket.HttpHeader()
                    {
                        Name        = HttpKnownHeaderNames.Upgrade,
                        NameLength  = (uint)HttpKnownHeaderNames.Upgrade.Length,
                        Value       = WebSocketValidate.WebSocketUpgradeToken,
                        ValueLength = (uint)WebSocketValidate.WebSocketUpgradeToken.Length
                    },
                    new Interop.WebSocket.HttpHeader()
                    {
                        Name        = HttpKnownHeaderNames.Host,
                        NameLength  = (uint)HttpKnownHeaderNames.Host.Length,
                        Value       = string.Empty,
                        ValueLength = 0
                    },
                    new Interop.WebSocket.HttpHeader()
                    {
                        Name        = HttpKnownHeaderNames.SecWebSocketVersion,
                        NameLength  = (uint)HttpKnownHeaderNames.SecWebSocketVersion.Length,
                        Value       = s_supportedVersion,
                        ValueLength = (uint)s_supportedVersion.Length
                    },
                    new Interop.WebSocket.HttpHeader()
                    {
                        Name        = HttpKnownHeaderNames.SecWebSocketKey,
                        NameLength  = (uint)HttpKnownHeaderNames.SecWebSocketKey.Length,
                        Value       = s_dummyWebsocketKeyBase64,
                        ValueLength = (uint)s_dummyWebsocketKeyBase64.Length
                    }
                };
            }
        }
예제 #23
0
        private static string GetLocalizedEventMessage(SafeLibraryHandle resourcesModule, uint messageId, IList <string> insertionStrings, CultureInfo language, TextWriter debugWriter)
        {
            if (resourcesModule == null)
            {
                throw new ArgumentNullException("resourcesModule");
            }
            if (resourcesModule.IsInvalid)
            {
                throw new ArgumentException("invalid resources module handle.", "resourcesModule");
            }
            if (debugWriter == null)
            {
                throw new ArgumentNullException("debugWriter");
            }
            uint num = 2304U;

            string[] array = new string[100];
            if (insertionStrings == null || insertionStrings.Count == 0)
            {
                num |= 512U;
            }
            else
            {
                num |= 8192U;
                for (int i = 0; i < insertionStrings.Count; i++)
                {
                    array[i] = insertionStrings[i];
                }
            }
            StringBuilder stringBuilder;
            int           num2 = NativeMethods.FormatMessage(num, resourcesModule, messageId, (uint)((language != null) ? language.LCID : 0), out stringBuilder, 0U, array);

            if (num2 == 0 || stringBuilder == null)
            {
                if (language != null && (long)Marshal.GetLastWin32Error() == 1815L)
                {
                    debugWriter.WriteLine(Strings.TenantNotificationDebugFormatMessageFailed(language));
                    num2 = NativeMethods.FormatMessage(num, resourcesModule, messageId, 0U, out stringBuilder, 0U, array);
                    if (num2 != 0 && stringBuilder != null)
                    {
                        return(stringBuilder.ToString().TrimEnd(Utils.CharsToTrim));
                    }
                }
                debugWriter.WriteLine(Strings.TenantNotificationDebugFormatMessageFailedSystemLang(Marshal.GetLastWin32Error()));
                return(string.Empty);
            }
            return(stringBuilder.ToString().TrimEnd(Utils.CharsToTrim));
        }
예제 #24
0
        //--------------------------------------------------------------
        #region Methods
        //--------------------------------------------------------------

        private string GetCaption(uint id)
        {
            if (_user32 == null)
            {
                _user32 = Win32.LoadLibrary(Environment.SystemDirectory + "\\User32.dll");
            }

            var sb = new StringBuilder(256);

            if (Win32.LoadString(_user32, id, sb, sb.Capacity) >= 0)
            {
                return(sb.ToString().Replace("&", ""));
            }

            return(string.Empty);
        }
예제 #25
0
        public SevenZipFormat(string sevenZipLibPath)
        {
            LibHandle = LoadLibrary(sevenZipLibPath);
            if (LibHandle.IsInvalid)
            {
                throw new Win32Exception();
            }

            IntPtr FunctionPtr = GetProcAddress(LibHandle, "GetHandlerProperty");

            // Not valid dll
            if (FunctionPtr == IntPtr.Zero)
            {
                LibHandle.Close();
                throw new ArgumentException();
            }
        }
예제 #26
0
        private string GetCaption(uint id)
        {
#pragma warning disable 618
            if (this.user32 is null)
            {
                this.user32 = UnsafeNativeMethods.LoadLibrary(Path.Combine(Environment.SystemDirectory, "User32.dll"));
            }

            var sb = new StringBuilder(256);
            if (UnsafeNativeMethods.LoadString(this.user32, id, sb, sb.Capacity) == 0)
            {
                sb.Clear();
                sb.AppendFormat("String with id '{0}' could not be found.", id);
            }
#pragma warning restore 618
            return(sb.ToString().Replace("&", string.Empty));
        }
예제 #27
0
        internal unsafe void CheckConsistencyHelper(IntPtr dsHandle, SafeLibraryHandle libHandle)
        {
            // call DsReplicaConsistencyCheck
            var replicaConsistencyCheck = (delegate * unmanaged <IntPtr, int, int, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaConsistencyCheck");

            if (replicaConsistencyCheck == null)
            {
                throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
            }

            int result = replicaConsistencyCheck(dsHandle, 0, 0);

            if (result != 0)
            {
                throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
            }
        }
예제 #28
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            bool valid_dll = false;

            try
            {
                using (SafeLibraryHandle lib = COMUtilities.SafeLoadLibrary(textBoxDbgHelp.Text))
                {
                    if (lib.GetFunctionPointer("SymInitializeW") != IntPtr.Zero)
                    {
                        valid_dll = true;
                    }
                }
            }
            catch (Win32Exception)
            {
            }

            if (!valid_dll)
            {
                MessageBox.Show(this, "Invalid DBGHELP.DLL file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (Environment.Is64BitProcess)
            {
                Properties.Settings.Default.DbgHelpPath64 = textBoxDbgHelp.Text;
            }
            else
            {
                Properties.Settings.Default.DbgHelpPath32 = textBoxDbgHelp.Text;
            }
            Properties.Settings.Default.SymbolPath        = textBoxSymbolPath.Text;
            Properties.Settings.Default.SymbolsConfigured = true;
            try
            {
                Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {
                Program.ShowError(this, ex);
            }
            DialogResult = DialogResult.OK;
            Close();
        }
예제 #29
0
        private static bool LoadBinFile(String fileName, out FilterData data)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException("fileName is null or empty.", nameof(fileName));
            }

            data = null;
            bool result = false;

            using (SafeLibraryHandle hm = UnsafeNativeMethods.LoadLibraryEx(fileName, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE))
            {
                if (!hm.IsInvalid)
                {
                    byte[] ffdata = null;

                    GCHandle gch          = GCHandle.Alloc(ffdata);
                    bool     needsRelease = false;
                    try
                    {
                        hm.DangerousAddRef(ref needsRelease);
                        IntPtr hMod = hm.DangerousGetHandle();
                        if (!UnsafeNativeMethods.EnumResourceNames(hMod, "PARM", new EnumResNameDelegate(EnumRes), GCHandle.ToIntPtr(gch)))
                        {
                            ffdata = (byte[])gch.Target;
                            if (ffdata != null)
                            {
                                data   = GetFilterDataFromParmBytes(ffdata);
                                result = true;
                            }
                        }
                    }
                    finally
                    {
                        gch.Free();
                        if (needsRelease)
                        {
                            hm.DangerousRelease();
                        }
                    }
                }
            }

            return(result);
        }
예제 #30
0
파일: HttpApi.cs 프로젝트: pa-at/aspnetcore
    private static void InitHttpApi(ushort majorVersion, ushort minorVersion)
    {
        version.HttpApiMajorVersion = majorVersion;
        version.HttpApiMinorVersion = minorVersion;

        var statusCode = HttpInitialize(version, (uint)(HTTP_FLAGS.HTTP_INITIALIZE_SERVER | HTTP_FLAGS.HTTP_INITIALIZE_CONFIG), null);

        supported = statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS;

        if (supported)
        {
            HttpApiModule          = SafeLibraryHandle.Open(HTTPAPI);
            HttpSetRequestProperty = HttpApiModule.GetProcAddress <HttpSetRequestPropertyInvoker>("HttpSetRequestProperty", throwIfNotFound: false);
            SupportsReset          = HttpSetRequestProperty != null;
            SupportsTrailers       = IsFeatureSupported(HTTP_FEATURE_ID.HttpFeatureResponseTrailers);
            SupportsDelegation     = IsFeatureSupported(HTTP_FEATURE_ID.HttpFeatureDelegateEx);
        }
    }
예제 #31
0
        public static string GetDllResourceString(string dllPath, int resourceId)
        {
            StringBuilder stringBuilder = new StringBuilder();

            using (SafeLibraryHandle safeLibraryHandle = SafeLibraryHandle.LoadLibrary(dllPath))
            {
                if (!safeLibraryHandle.IsInvalid)
                {
                    int num = NativeMethods.LoadString(safeLibraryHandle, resourceId, stringBuilder, 0);
                    if (num != 0)
                    {
                        stringBuilder.EnsureCapacity(num + 1);
                        NativeMethods.LoadString(safeLibraryHandle, resourceId, stringBuilder, stringBuilder.Capacity);
                    }
                }
            }
            return(stringBuilder.ToString());
        }
예제 #32
0
 private static extern IntPtr dlsym(SafeLibraryHandle handle, IntPtr symbol);
예제 #33
0
파일: User32.cs 프로젝트: AArnott/pinvoke
 public static extern unsafe IntPtr CreateDialogIndirectParam(
     SafeLibraryHandle hInstance,
     DLGTEMPLATE* lpTemplate,
     IntPtr hWndParent,
     DialogProc lpDialogFunc,
     IntPtr lParamInit);
예제 #34
0
 public static extern int LoadString(SafeLibraryHandle hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
예제 #35
0
 public static extern IntPtr GetProcAddress(
     SafeLibraryHandle hModule,
     [MarshalAs(UnmanagedType.LPStr)] string procName);
예제 #36
0
파일: Kernel32.cs 프로젝트: vbfox/pinvoke
 public static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, string procName);
 internal static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, [In, MarshalAs(UnmanagedType.LPStr)]string lpProcName);
예제 #38
0
        //
        // TryGetLocalizedNameByNativeResource -
        //
        // Helper function for retrieving a localized string resource via a native resource DLL.
        // The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
        //
        // "resource.dll" is a language-specific resource DLL.
        // If the localized resource DLL exists, LoadString(resource) is returned.
        //
        static unsafe private string TryGetLocalizedNameByNativeResource(string filePath, int resource)
        {
            fixed (char* file = filePath.ToCharArray())
            {
                using (SafeLibraryHandle handle =
                           new SafeLibraryHandle(Interop.mincore.LoadLibraryEx(file, IntPtr.Zero, Interop.mincore.LOAD_LIBRARY_AS_DATAFILE)))
                {
                    if (!handle.IsInvalid)
                    {
                        StringBuilder localizedResource = StringBuilderCache.Acquire(Interop.mincore.LOAD_STRING_MAX_LENGTH);
                        localizedResource.Length = Interop.mincore.LOAD_STRING_MAX_LENGTH;

                        int result = Interop.mincore.LoadString(handle, resource,
                                         localizedResource, localizedResource.Length);

                        if (result != 0)
                        {
                            return StringBuilderCache.GetStringAndRelease(localizedResource);
                        }
                    }
                }
            }
            return String.Empty;
        }
예제 #39
0
        //
        // GetBrowserToken not required because that is accomplished via Pheonix bit etc. (not exposed thru
        // managed interface).
        // 

        //
        // Summary:
        // Performs initialization of the CardSpaceShim if necessary.
        // The v1 service will only allow one request from the user,
        // however locking anyway in case we change our behavior in v2.
        //
        public void InitializeIfNecessary()
        {
            if (!m_isInitialized)
            {
                lock (m_syncRoot)
                {
                    if (!m_isInitialized)
                    {
                        string implDllPath = GetCardSpaceImplementationDll();

                        m_implementationDll = SafeLibraryHandle.LoadLibraryW(implDllPath);
                        if (m_implementationDll.IsInvalid)
                        {
                            throw NativeMethods.ThrowWin32ExceptionWithContext(new Win32Exception(), implDllPath);
                        }

                        try
                        {
                            //
                            // Functions are listed in alphabetical order
                            //

                            IntPtr procaddr1 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "CloseCryptoHandle");
                            m_csShimCloseCryptoHandle =
                                (CsV2CloseCryptoHandle)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr1, typeof(CsV2CloseCryptoHandle));

                            IntPtr procaddr2 = NativeMethods.GetProcAddressWrapper(
                                m_implementationDll, "Decrypt");
                            m_csShimDecrypt =
                                (CsV2Decrypt)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr2, typeof(CsV2Decrypt));

                            IntPtr procaddr3 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "Encrypt");
                            m_csShimEncrypt =
                                (CsV2Encrypt)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr3, typeof(CsV2Encrypt));

                            IntPtr procaddr4 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "FreeToken");
                            m_csShimFreeToken =
                                (CsV2FreeToken)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr4, typeof(CsV2FreeToken));

                            IntPtr procaddr5 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "GenerateDerivedKey");
                            m_csShimGenerateDerivedKey =
                                (CsV2GenerateDerivedKey)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr5, typeof(CsV2GenerateDerivedKey));

                            IntPtr procaddr6 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "GetCryptoTransform");
                            m_csShimGetCryptoTransform =
                                (CsV2GetCryptoTransform)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr6, typeof(CsV2GetCryptoTransform));

                            IntPtr procaddr7 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "GetKeyedHash");
                            m_csShimGetKeyedHash =
                                (CsV2GetKeyedHash)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr7, typeof(CsV2GetKeyedHash));

                            IntPtr procaddr8 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "GetToken");
                            m_csShimGetToken =
                                (CsV2GetToken)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr8, typeof(CsV2GetToken));

                            IntPtr procaddr9 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "HashCore");
                            m_csShimHashCore =
                                (CsV2HashCore)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr9, typeof(CsV2HashCore));

                            IntPtr procaddr10 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "HashFinal");
                            m_csShimHashFinal =
                                (CsV2HashFinal)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr10, typeof(CsV2HashFinal));

                            IntPtr procaddr11 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "ImportInformationCard");
                            m_csShimImportInformationCard =
                                (CsV2ImportInformationCard)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr11, typeof(CsV2ImportInformationCard));

                            IntPtr procaddr12 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "ManageCardSpace");
                            m_csShimManageCardSpace =
                                (CsV2ManageCardSpace)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr12, typeof(CsV2ManageCardSpace));

                            IntPtr procaddr13 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "SignHash");
                            m_csShimSignHash =
                                (CsV2SignHash)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr13, typeof(CsV2SignHash));

                            IntPtr procaddr14 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "TransformBlock");
                            m_csShimTransformBlock =
                                (CsV2TransformBlock)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr14, typeof(CsV2TransformBlock));

                            IntPtr procaddr15 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "TransformFinalBlock");
                            m_csShimTransformFinalBlock =
                                (CsV2TransformFinalBlock)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr15, typeof(CsV2TransformFinalBlock));


                            IntPtr procaddr16 = NativeMethods.GetProcAddressWrapper(m_implementationDll, "VerifyHash");
                            m_csShimVerifyHash =
                                (CsV2VerifyHash)Marshal.GetDelegateForFunctionPointer(
                                                            procaddr16, typeof(CsV2VerifyHash));

                        }
                        catch (Win32Exception)
                        {
                            //
                            // NB: IDT.ThrowHelperError would have logged for the Win32Exception
                            //
                            IDT.Assert(!m_isInitialized, "If an exception occurred, we expect this to be false");
                            throw;
                        }

                        m_isInitialized = true;
                    }
                }
            }
        }
예제 #40
0
        // FormatMessageW will AV if you don't pass in enough format strings.  If you call TryFormatMessage we ensure insertionStrings
        // is long enough.  You don't want to call this directly unless you're sure insertionStrings is long enough!
        internal static string UnsafeTryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) {
            string msg = null;

            int msgLen = 0;
            StringBuilder buf = new StringBuilder(1024);
            int flags = NativeMethods.FORMAT_MESSAGE_FROM_HMODULE | NativeMethods.FORMAT_MESSAGE_ARGUMENT_ARRAY;

            IntPtr[] addresses = new IntPtr[insertionStrings.Length];
            GCHandle[] handles = new GCHandle[insertionStrings.Length];
            GCHandle stringsRoot = GCHandle.Alloc(addresses, GCHandleType.Pinned);

            // Make sure that we don't try to pass in a zero length array of addresses.  If there are no insertion strings, 
            // we'll use the FORMAT_MESSAGE_IGNORE_INSERTS flag . 
            // If you change this behavior, make sure you look at TryFormatMessage which depends on this behavior!
            if (insertionStrings.Length == 0) {
                flags |= NativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS;
            }
            
            try {
                for (int i=0; i<handles.Length; i++) {
                    handles[i] = GCHandle.Alloc(insertionStrings[i], GCHandleType.Pinned);
                    addresses[i] = handles[i].AddrOfPinnedObject();
                }
                int lastError = NativeMethods.ERROR_INSUFFICIENT_BUFFER;
                while (msgLen == 0 && lastError == NativeMethods.ERROR_INSUFFICIENT_BUFFER) {
                    msgLen = SafeNativeMethods.FormatMessage(
                        flags,
                        hModule,
                        messageNum,
                        0,
                        buf,
                        buf.Capacity,
                        addresses);

                    if (msgLen == 0) {
                        lastError = Marshal.GetLastWin32Error();
                        if (lastError == NativeMethods.ERROR_INSUFFICIENT_BUFFER)
                            buf.Capacity = buf.Capacity * 2;
                    }
                }
            }
            catch {
                msgLen = 0;              // return empty on failure
            }
            finally  {
                for (int i=0; i<handles.Length; i++) {
                    if (handles[i].IsAllocated) handles[i].Free();
                }
                stringsRoot.Free();
            }
            
            if (msgLen > 0) {
                msg = buf.ToString();
                // chop off a single CR/LF pair from the end if there is one. FormatMessage always appends one extra.
                if (msg.Length > 1 && msg[msg.Length-1] == '\n')
                    msg = msg.Substring(0, msg.Length-2);
            }

            return msg;
        }
예제 #41
0
파일: Kernel32.cs 프로젝트: AArnott/pinvoke
 public static extern IntPtr LoadResource(SafeLibraryHandle hModule, IntPtr hResInfo);
 internal static extern int LoadString(SafeLibraryHandle handle, int id, StringBuilder buffer, int bufferLength);
예제 #43
0
 static public IntPtr GetProcAddress(SafeLibraryHandle dllHandle, string name) {
     // clear previous errors if any
     dlerror();
     var res = dlsym(dllHandle, name);
     var errPtr = dlerror();
     if (errPtr != IntPtr.Zero) {
         throw new Exception("dlsym: " + Marshal.PtrToStringAnsi(errPtr));
     }
     return res;
 }
예제 #44
0
 internal static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, String procname);
예제 #45
0
 private static extern IntPtr GetProcAddress(SafeLibraryHandle moduleHandle, string procname);
예제 #46
0
 public static IntPtr LoadProcedure(SafeLibraryHandle handle, string functionName)
 {
     return GetProcAddress(handle, functionName);
 }
예제 #47
0
        //--------------------------------------------------------------
        private string GetCaption(uint id)
        {
            if (_user32 == null)
                _user32 = Win32.LoadLibrary(Environment.SystemDirectory + "\\User32.dll");

            var sb = new StringBuilder(256);
            if (Win32.LoadString(_user32, id, sb, sb.Capacity) >= 0)
                return sb.ToString().Replace("&", "");

            return string.Empty;
        }
예제 #48
0
        // Format message in specific DLL. Return <null> on failure.
        internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) {

            if (insertionStrings.Length == 0) {
                // UnsafeTryFromatMessage will set FORMAT_MESSAGE_IGNORE_INSERTS when calling into the OS 
                // when there are no insertion strings, in this case we don't have to guard against insertionStrings
                // not having enough data since it is unused when FORMAT_MESSAGE_IGNORE_INSERTS is specified
                return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings);
            }

            // If you pass in an empty array UnsafeTryFormatMessage will just pull out the message.
            string formatString = UnsafeTryFormatMessage(hModule, messageNum, new string[0]);

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

            int largestNumber = 0;

            for (int i = 0; i < formatString.Length; i++) {
                if (formatString[i] == '%') {
                    // See if a number follows this, if so, grab the number.
                    if(formatString.Length > i + 1) {
                        StringBuilder sb = new StringBuilder();
                        while (i + 1 < formatString.Length && Char.IsDigit(formatString[i + 1])) {
                            sb.Append(formatString[i + 1]);
                            i++;
                        }

                        // move over the non number character that broke us out of the loop
                        i++;

                        if (sb.Length > 0) {
                            int num = -1;
                            if (Int32.TryParse(sb.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out num)) {
                                largestNumber = Math.Max(largestNumber, num);
                            }
                        }
                    }
                }
            }

            // Replacement strings are 1 indexed.
            if (largestNumber > insertionStrings.Length) {
                string[] newStrings = new string[largestNumber];
                Array.Copy(insertionStrings, newStrings, insertionStrings.Length);
                for (int i = insertionStrings.Length; i < newStrings.Length; i++) {
                    newStrings[i] = "%" + (i + 1);
                }

                insertionStrings = newStrings;
            }

            return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings);
        }
 internal static extern int FormatMessage
 (
     int dwFlags,
     SafeLibraryHandle lpSource,
     int dwMessageId,
     int dwLanguageId,
     StringBuilder lpBuffer,
     int nSize,
     IntPtr arguments
 );
예제 #50
0
			public static IntPtr LoadProcedure(SafeLibraryHandle libHandle, string functionName)
			{
				throw new NotSupportedException();
			}