Adddll mingw32 or dependencies not loaded win32 error 126

Summary GHC 9.4.4 causes below error when compiling the code which depend on both file-embed and proteaaudio package on Windows, while...

Summary

GHC 9.4.4 causes below error when compiling the code which depend on both file-embed and proteaaudio package on Windows, while GHC 8.10.7 does not.

<no location info>: error:
    addDLL: stdc++ or dependencies not loaded. (Win32 error 126)

Individually, these packages can be compiled and executed with no problem.
Especially, generated sample executable for proteaaudio runs fine.

However, when both file-embed and proteaaudio are added to build-depends field of .cabal file, below trivial code does not compile with above error:

{-# LANGUAGE TemplateHaskell #-}
module Main where

import Data.FileEmbed
import Data.ByteString (ByteString)

main :: IO ()
main = putStrLn "Hello World!"

buffer :: ByteString -- not used
buffer = $(embedFile "data/mm2_1401.wav")

Steps to reproduce

% git clone https://github.com/wkoiking/proteaaudio-test.git
% cd proteaaudio-test
% stack build

When the code depends only on proteaaudio, the error does not occur.
Which can be checked by:

% git checkout 765abc2
% stack run

Expected behavior

The compilation should succeed without error.

Environment

GHC version used: GHC 9.4.4

Optional:

Operating System: Windows 10 Home (10.0.19044 build 19044)
System Architecture: x86_64

You have a new package you want to try out. You try to install the package only to be greeted with

GHCi, version 8.2.2: http://www.haskell.org/ghc/  :? for help
<command line>: user specified .o/.so/.DLL could not be loaded (addDLL: my-cool-library or dependencies not loaded. (Win32 error 126))
Whilst trying to load:  (dynamic) my-cool-library
Additional directories searched: (none)

by GHCi. Confused you look into your libraries folder and see my-cool-library-7.dll. Why is the file name incorrect? Why is GHCi looking for my-cool-library.dll instead of my-cool-library-7.dll.

You rename the file and things seem to work. This is actually quite dangerous and wrong. Unfortunately this is also often suggested as what to do.

To understand why you should not do this, let’s take a step back and give a crash course on linkers.

Import Libraries

First off, let’s talk about what you should be giving to the compiler.
On Unix systems the shared library contains internally the PLT and the GOT sections along with the binding
method required. On Windows, this information is externalized into a file called an import library.

All Microsoft compilers will only accept import libraries to link against. Unfortunately Binutils also accepts DLLs
directly, mostly due to historical reasons.

When it comes to import libraries there are two versions:

  1. The official format is documented in the Microsoft PE
    specification. Libraries produced by this format typically contain the file extension .lib.
  2. The second format is an unofficial format invited by and only supported by GNU tools. This format is based on the normal object code format and typically result in larger and more inefficient libraries. Libraries in this format typically end with the extensions .dll.a or .a depending on the tool that created them. They work using a hack around pseudo symbols that start with _head_ in the name. GHC and GCC support both formats.

So what is one supposed to do when you only have a DLL? Create an import library from the Microsoft DEF file.
https://msdn.microsoft.com/en-us/library/28d6s79h.aspx and when creating a shared library, always ask the compiler
to also produce an import library! (This is the default for GHC and Microsoft compilers.)

DLL Hell

Before Microsoft solved “DLL” hell once and for all using side-by-side assemblies, different projects used import libraries to support multiple versions of the same DLL on the same system at the same time. They did this by versioning the DLL by adding information to the name of the DLL to make them unique. e.g. to support multiple versions of my-cool-library on the user’s machine the DLLs would be named my-cool-library-1.dll, my-cool-library-2.dll,..,my-cool-library-n.dll. The import library would be named my-cool-library.lib so that -lmy-cool-library still works.

The import library will point the linker to which version of the DLL to enter into the program’s IAT. The Import Address Table contains a list of DLL and symbols to import from each.

GHC knows how to properly deal with these redirects.

Lazy loading

As I mentioned before, Windows externalizes the binding type. Windows defaults to strict binding, i.e. when the program starts up it forces the resolution of all symbols. Including ones you may never need.

Lazy bindings (which is the default in System-V) is also supported via the import library. This is a choice made by
the programmer during library creation time. When lazy loading the library gets a chance to resolve each symbol. This allows it to do symbol resolution and redirection.

When linking directly against a DLL you may be changing the semantics of the library due to it switch from lazy to eager binding.

Relocations

On any given compilation pipeline you generally have three main phases. compiling, assembling and linking. Input source files like .hs and .c files are compiled into assembly language for the given target in the first phase. The compiler has no idea where the functions that are defined in another source or library actually is. The compiler simply emits a call or branch to the symbol.

Let’s look at an example. The following C file

#include <stdio.h>

int main ()
{
   printf("Hello World");
}

gets compiled into the following x86_64 assembly file

.LC0:
        .ascii "Hello World"
        .text
        .globl  main
main:
        pushq   %rbp
        movq    %rsp, %rbp
        subq    $32, %rsp
        call    __main
        leaq    .LC0(%rip), %rcx
        call    printf
        movl    $0, %eax
        addq    $32, %rsp
        popq    %rbp
        ret

This assembly file is then given to the assembler which will produce object code. Since it doesn’t know the address of these function it emits what’s called a relocation against the symbol¹.

¹ In general any function or global data reference is called a symbol.

If we look at the object file we’ll get our first hint of the relocation:

Disassembly of section .text:

0000000000000000 <main>:
   0:   55                      push   %rbp
   1:   48 89 e5                mov    %rsp,%rbp
   4:   48 83 ec 20             sub    $0x20,%rsp
   8:   e8 00 00 00 00          callq  d <main+0xd>
                        9: R_X86_64_PC32        __main
   d:   48 8d 0d 00 00 00 00    lea    0x0(%rip),%rcx        # 14 <main+0x14>
                        10: R_X86_64_PC32       .rdata
  14:   e8 00 00 00 00          callq  19 <main+0x19>
                        15: R_X86_64_PC32       printf
  19:   b8 00 00 00 00          mov    $0x0,%eax
  1e:   48 83 c4 20             add    $0x20,%rsp
  22:   5d                      pop    %rbp
  23:   c3                      retq

As we can see the assembler has emitted a relocation R_X86_64_PC32 against the printf symbol. The important thing to note here is that this is a Program Counter relative 32-bit relocation. It means the address of the symbol MUST fit within a 32-bit offset. Put it this way, the function must be within a 4GB offset from the current instruction.

The final step in this process is the linker that is responsible to finding the the functions used. This step is called symbol resolution. For GHCi and Template Haskell, the GHC runtime has it’s own runtime linker.

We don’t need to continue beyond this point, but the 32-bit relocation is important to note.

Preferred Image base

On a conceptual level, the linking model between Windows and Unix (System-V) are reasonably close, however
implementation wise things are rather different. Windows for one doesn’t have PIC (Position Independent Code)
but has a concept of rebasing. Essentially what this means is that when the PE file’s preferred load address
is already taken the file will be rebased to a new address. When ASLR is enabled the image base is randomly
chosen.

Why is this important? Because on 64-bit Windows the preferred load address for shared libraries created with
a Microsoft compiler is 0x180000000. Which means the address is larger than would fit in a 32-bit address.

Linking against a DLL directly can, and most often will result in the address being truncated to fit the R_X86_64_PC32 relocation. This is why you should never do this. It is unfortunate, but binutils will allow you to link directly against a DLL (mostly for historical reasons.) but will emit a rather cryptic warning:

relocation truncated to fit: R_X86_64_PC32 against `<symbol>'

This warning essentially means the address it is using for the DLL is likely invalid! This will result in a segfault at runtime if you’re lucky, at worse a random function being called.

When the linker does warn you and you ignore it, this is what typically happens

Access violation in generated code when executing data at 000000008000fb50

It may not happen the first, or second time, but eventually it will due to ASLR moving around the library. As a concrete example, the official PostGres libraries are compiled using a Microsoft compiler. As such it’s image base is in the low 64-bit range.

0x000ab360: C:Program FilesPostgreSQL10binLIBPQ.dll
      Base   0x180000000  EntryPoint  0x180021968  Size        0x00049000    DdagNode     0x000ab4b0
      Flags  0x000c22ec  TlsIndex    0x00000000  LoadCount   0x00000001    NodeRefCount 0x00000000
             <unknown>
             LDRP_LOAD_NOTIFICATIONS_SENT
             LDRP_IMAGE_DLL
             LDRP_DONT_CALL_FOR_THREADS
             LDRP_PROCESS_ATTACH_CALLED

To illustrate the difference between linking directly against the DLL and against the import table let’s look
at this example program:

#include <stdio.h>
#include <stdint.h>

extern void* PQgetvalue (void);

int main () {
  printf ("PQgetvalue: %p", PQgetvalue);
}

This program reports the address of the symbol PQgetvalue.
When linking directly against the DLL the address returned is

Tamar@Rage MINGW64 /r
$ gcc test.c -o test -lpq -L/E/Program Files/PostgreSQL/10/lib/
Tamar@Rage MINGW64 /r
$ ./test.exe
PQgetvalue: 00000000`6440CDE0

The function PQgetvalue is actually at address 0x000000018000fb50 but has been truncated to 0x8000fb50.
This is why it segfaults.

However when linking against the import library explicitly

Tamar@Rage MINGW64 /r
$ gcc test.c -o test -llibpq -L/E/Program Files/PostgreSQL/10/lib/
Tamar@Rage MINGW64 /r
$ ./test.exe
PQgetvalue: 00000000`004015A0

you get an address far inside the 32-bit range as expected.

GHCi is able to correctly handle function symbols when given a DLL to load. That is, we create a trampoline/indirection on any symbol required from a DLL. The trampoline is ensured to be created in
the 4GB range and will then use a jmp to any 64-bit location. If there’s no more space in the 4GB range
we abort. However GHCi cannot know from just the DLL what the original semantics of all the symbols in the
export table of the DLL is. It is forced to assume everything is a function.

Import library essentially contain stubs, or direct the linker to emit stubs within the program’s .text section.
This ensures that the stub itself is within range of the R_X86_64_PC32 relocation and that the truncation doesn’t happen.

Data references (GOT)

Like System-V, Windows allows data to be exported from the DLL. However, because data is accessed directly we cannot use an indirection to access the data. The address returned for the symbol must be the symbol itself.

Which means when using a relocation, it must point to the data directly. The compiler knows about which symbols
are data and which are functions, and will appropriately mark them so in the import library.

If GHC or Binutils is given a DLL directly, they have no way to determine this information. If this were to happen
then you would access the redirection instead of the data value you were expecting.

Library Search Order

On all platforms, including Windows we do honor the LD_LIBRARY_PATH and LIBRARY_PATH environment variables.
LD_LIBRARY_PATH will be used to look for shared dynamic libraries and LIBRARY_PATH for static archives and
import libraries. We also search the user PATH and extra-lib-dirs along with any paths given via -L.

The current search order in GHCi is:

For non-Haskell libraries (e.g. gmp, iconv):
first look in library-dirs for a dynamic library (on User paths only)
(libfoo.so)
then  try looking for import libraries on Windows (on User paths only)
(.dll.a, .lib)
first look in library-dirs for a dynamic library (on GCC paths only)
(libfoo.so)
then  check for system dynamic libraries (e.g. kernel32.dll on windows)
then  try looking for import libraries on Windows (on GCC paths only)
(.dll.a, .lib)
then  look in library-dirs for a static library (libfoo.a)
then look in library-dirs and inplace GCC for a dynamic library (libfoo.so)
then  try looking for import libraries on Windows (.dll.a, .lib)
then  look in library-dirs and inplace GCC for a static library (libfoo.a)
then  try "gcc --print-file-name" to search gcc's search path
    for a dynamic library (#5289)
otherwise, assume loadDLL can find it

The logic is a bit complicated, but the rationale behind it is that
loading a shared library for us is O(1) while loading an archive is
O(n). Loading an import library is also O(n) so in general we prefer
shared libraries because they are simpler and faster.

This has been tweaked through bug reports from various different releases. For most user libraries
we will do the right thing as long as you don’t give it a path to your DLL but an import library.
The current search directory is assuming any dll you give it only has functions. In the future I’d like to
promote the searching for import libraries above shared libraries.

For now this order is safe for the majority of cases as we do extra work to ensure loading a dll directly will
work for the majority of cases. In the mean time before we change the order (and ignore backwards compatibility)
you can control which one it picks using different paths for linking and running.

To figure out where GHCi searched for libraries just pass it an extra -v

*** gcc:
"E:msys64mingw64lib/../mingw/bin/gcc.exe" "-fno-stack-protector" "-DTABLES_NEXT_TO_CODE" "--print-file-name" "my-cool-library.lib"
*** gcc:
"E:msys64mingw64lib/../mingw/bin/gcc.exe" "-fno-stack-protector" "-DTABLES_NEXT_TO_CODE" "--print-file-name" "libmy-cool-library.lib"
*** gcc:
"E:msys64mingw64lib/../mingw/bin/gcc.exe" "-fno-stack-protector" "-DTABLES_NEXT_TO_CODE" "--print-file-name" "libmy-cool-library.dll.a"
*** gcc:
"E:msys64mingw64lib/../mingw/bin/gcc.exe" "-fno-stack-protector" "-DTABLES_NEXT_TO_CODE" "--print-file-name" "my-cool-library.dll.a"
*** gcc:
"E:msys64mingw64lib/../mingw/bin/gcc.exe" "-fno-stack-protector" "-DTABLES_NEXT_TO_CODE" "--print-file-name" "my-cool-library.dll"
*** gcc:
"E:msys64mingw64lib/../mingw/bin/gcc.exe" "-fno-stack-protector" "-DTABLES_NEXT_TO_CODE" "--print-file-name" "libmy-cool-library.dll"
*** gcc:
"E:msys64mingw64lib/../mingw/bin/gcc.exe" "-fno-stack-protector" "-DTABLES_NEXT_TO_CODE" "--print-file-name" "libmy-cool-library.a"
*** gcc:
"E:msys64mingw64lib/../mingw/bin/gcc.exe" "-fno-stack-protector" "-DTABLES_NEXT_TO_CODE" "--print-file-name" "my-cool-library.a"
Loading object (dynamic) my-cool-library ... failed.
*** Deleting temp files:
Deleting:
*** Deleting temp dirs:
Deleting:
<command line>: user specified .o/.so/.DLL could not be loaded (addDLL: my-cool-library or dependencies not loaded. (Win32 error 126))
Whilst trying to load:  (dynamic) my-cool-library
Additional directories searched: (none)

So where does the error you as the user sees comes from? When GHC’s runtime linker cannot find the path to a
library, it is forced to assume the library must be a DLL on the user’s system search path. The error 126
comes from the Windows loader which means

ERROR_MOD_NOT_FOUND

    126 (0x7E)

    The specified module could not be found.

More at https://docs.microsoft.com/en-us/windows/desktop/Debug/system-error-codes—0-499-

Error 126 can be caused because it either can’t find the DLL or one of it’s transitive dependencies.
To figure out the exact reason for the failure one can enable loader snaps and get debug output from
the Windows’s dynamic loader.

Conclusion

Hopefully this has shown why the GHC runtime linker is unable to find your DLL and how to do proper linking on Windows. If there’s anything I hope people take away from this it’s: never link directly against a dll on Windows.

Starting with GHC 7.10.x I have started to add import library support to GHC. With GHC 8.x this work has been
mostly completed. The remaining issues are just internal organization issues rather than functional changes.

This work is also the basis of getting a dynamically linked GHC to work on Windows. More on this at a later date.

I tried the following experiment, but it was a blind alley. I am using a version of stack built from the current master branch with GHC 9.0.2/Cabal-3.4.1.0. I created a simple project pkgTest (stack new pkgTest, which — today — uses lts-19.7) and added a dependency on acme-missiles-0.3, so that Main.hs became:

module Main where

import Lib
import Acme.Missiles

main :: IO ()
main = do
  someFunc
  launchMissiles

stack build creates a snapshot in the stack root (for me) at C:srsnapshots0e41759 and I looked at that with stack exec -- ghc-pkg dump -f C:srsnapshots0e41759pkgdb, yielding:

name:                 acme-missiles
version:              0.3
visibility:           public
id:                   acme-missiles-0.3-KfaH05Ue1Cs8dT7ALloWDX
key:                  acme-missiles-0.3-KfaH05Ue1Cs8dT7ALloWDX
license:              LicenseRef-PublicDomain
maintainer:           joeyadams3.14159@gmail.com
author:               Joey Adams
synopsis:             Cause serious international side effects.
description:
    The highly effectful 'launchMissiles' action, as mentioned in /Beautiful concurrency/,
    Simon Peyton Jones, 2007.

category:             Acme
abi:                  b249e6658759461df541cdd5c2e3aeba
exposed:              True
exposed-modules:      Acme.Missiles Acme.Missiles.STM
import-dirs:
    C:srsnapshots0e41759libx86_64-windows-ghc-9.0.2acme-missiles-0.3-KfaH05Ue1Cs8dT7ALloWDX

library-dirs:
    C:srsnapshots0e41759libx86_64-windows-ghc-9.0.2acme-missiles-0.3-KfaH05Ue1Cs8dT7ALloWDX
    C:UsersmikeAppDataLocalProgramsstackx86_64-windowsmsys2-20210604mingw64lib
    C:UsersmikeAppDataLocalProgramsstackx86_64-windowsmsys2-20210604mingw64bin

dynamic-library-dirs:
    C:srsnapshots0e41759libx86_64-windows-ghc-9.0.2
    C:UsersmikeAppDataLocalProgramsstackx86_64-windowsmsys2-20210604mingw64lib
    C:UsersmikeAppDataLocalProgramsstackx86_64-windowsmsys2-20210604mingw64bin

data-dir:
    C:srsnapshots0e41759sharex86_64-windows-ghc-9.0.2acme-missiles-0.3

hs-libraries:         HSacme-missiles-0.3-KfaH05Ue1Cs8dT7ALloWDX
include-dirs:
    C:UsersmikeAppDataLocalProgramsstackx86_64-windowsmsys2-20210604mingw64include

depends:              base-4.15.1.0 stm-2.5.0.0
haddock-interfaces:
    C:srsnapshots0e41759docacme-missiles-0.3acme-missiles.haddock

haddock-html:         C:srsnapshots0e41759docacme-missiles-0.3
pkgroot: "C:\\sr\snapshots\00e41759"

So, entries (a) in a file in my stack root (b) with paths to my existing stack-supplied MSYS2 (which is in msys2-20210604). Perhaps that was the cause of what @andreasabel was observing?

I investigated what happened if I disabled that MSYS2:

stack path --programs | cd
ren msys2-20210604 msys2-20210604.old
ren msys2-20210604.installed msys2-20210604.installed.old

Back in the project folder, stack build now (a) identified the missing MSYS2 and downloaded the latest MSYS2-20220503, and (b) yielded this (but no ghc.exe: addLibrarySearchPath errors reported):

pkgTest-0.1.0.0: unregistering (flags changed from ["--extra-include-dirs=C:\Users\mike\AppData\Local\Programs\stack\x86_64-windows\msys2-20210604\mingw64\include","--extra-lib-dirs=C:\Users\mike\AppData\Local\Programs\stack\x86_64-windows\msys2-20210604\mingw64\lib","--extra-lib-dirs=C:\Users\mike\AppData\Local\Programs\stack\x86_64-windows\msys2-20210604\mingw64\bin"] to ["--extra-include-dirs=C:\Users\mike\AppData\Local\Programs\stack\x86_64-windows\msys2-20220503\mingw64\include","--extra-lib-dirs=C:\Users\mike\AppData\Local\Programs\stack\x86_64-windows\msys2-20220503\mingw64\lib","--extra-lib-dirs=C:\Users\mike\AppData\Local\Programs\stack\x86_64-windows\msys2-20220503\mingw64\bin"])
pkgTest> configure (lib + exe)
Configuring pkgTest-0.1.0.0...
pkgTest> build (lib + exe)
Preprocessing library for pkgTest-0.1.0.0..
Building library for pkgTest-0.1.0.0..
[1 of 2] Compiling Lib [flags changed]
[2 of 2] Compiling Paths_pkgTest [flags changed]
Preprocessing executable 'pkgTest-exe' for pkgTest-0.1.0.0..
Building executable 'pkgTest-exe' for pkgTest-0.1.0.0..
[1 of 2] Compiling Main [flags changed]
[2 of 2] Compiling Paths_pkgTest [flags changed]
Linking .stack-workdistd53b6a14buildpkgTest-exepkgTest-exe.exe ...
pkgTest> copy/register
Installing library in D:UsersmikeCodeHaskellpkgTest.stack-workinstalla7a5ad27libx86_64-windows-ghc-9.0.2pkgTest-0.1.0.0-EYjhW8QjuAYDzydfO0o2wU
Installing executable pkgTest-exe in D:UsersmikeCodeHaskellpkgTest.stack-workinstalla7a5ad27bin
Registering library for pkgTest-0.1.0.0..

When I tried stack exec -- ghc-pkg dump -f C:srsnapshots0e41759pkgdb again, I had the same result as before — with the same paths to the old — now non-existent — C:UsersmikeAppDataLocalProgramsstackx86_64-windowsmsys2-20210604. stack and ghc did not seem to be troubled by that.

If I deleted C:srsnapshots0e41759, stack build recreated it — but this time with paths to the new C:UsersmikeAppDataLocalProgramsstackx86_64-windowsmsys2-20220503

I tried the same thing but with a stack purge after disabling the existing MSYS2 and had the same result: stack and ghc did not seem troubled by C:srsnapshots0e41759pkgdb containing references to paths that no longer existed.

I’m using the ‘LoadLibrary’ from the Windows API, when I run the application, it throws me an error code 126. I read that it may be caused by dependencies, I checked what’s wrong with some applications like Dependency Walker, but everything was fine.

LoadLibrary in the application:

            HMODULE dll_mod = LoadLibrary(L"path_to_dll");
            if(dll_mod==NULL){
                std::stringstream error;
                error << "Could not load plugin located at:n" << file_full.toStdString() << "n" << "Error Code: " << GetLastError();
                FreeLibrary(dll_mod);
                return error.str();
            }

Plugin code:

#include "stdafx.h"
#define DLL_EXPORT
#define PLUGIN_STREAM __declspec(dllexport)
#include <iostream>
#include <vector>
using std::vector;
using std::string;
// Init event (After the loading)
extern "C"{
PLUGIN_STREAM int onInit(char* argv){
return 0;
}
PLUGIN_STREAM void pluginInfo(vector<string> & info){
info.push_back("media_event=false");
    info.push_back("status_event=false");
    info.push_back("send_event=true");
    info.push_back("plugin_name='RadioStream'");
    info.push_back("description='This plugin was designed for that people that wants to listen to radio music.nYou can register your radio and play it later, also we have a gallery of radios that you can check.nThis plugin is original of Volt and it's originally implemented in the application.'");
    info.push_back("success:0");
    info.push_back("error:1=Could not open data file");
    info.push_back("error:2=Could not prepare plugin");
    info.push_back("alert:40=Could not connect to that radio");
}
}

Jean-François Corbett's user avatar

asked Jan 16, 2013 at 15:32

Spamdark's user avatar

5

Windows dll error 126 can have many root causes.
The most useful methods I have found to debug this are:

  1. Use dependency walker to look for any obvious problems (which you
    have already done)
  2. Use the sysinternals utility Process Monitor https://learn.microsoft.com/en-us/sysinternals/downloads/procmon from Microsoft to trace all file access while your dll is trying to load. With this utility, you will see everything that that dll is trying to pull in and usually the problem can be determined from there.

Eric Duminil's user avatar

Eric Duminil

52.1k8 gold badges67 silver badges120 bronze badges

answered Jan 16, 2013 at 15:46

DanS's user avatar

DanSDanS

1,1911 gold badge8 silver badges4 bronze badges

12

This can also happen when you’re trying to load a DLL and that in turn needs another DLL which cannot be not found.

answered Apr 7, 2020 at 3:40

Shivanshu Goyal's user avatar

Shivanshu GoyalShivanshu Goyal

1,3142 gold badges16 silver badges22 bronze badges

This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.

bluish's user avatar

bluish

25.7k27 gold badges119 silver badges177 bronze badges

answered Sep 19, 2017 at 9:10

Iacopo Braccesi's user avatar

In my case it was all about character sets v.s. form of loader function. This is visual studio 2019 setting at Project/Properties/Configuration Properties/Advanced/Character Set which has two choices:

1.Use Multi-Byte Character Set ->call it mb

2.Use Unicode Character Set -> call it uc

 My test revealed:
      const char*  fileName =  ".\Debug\Win32\Dll1.dll";
    
         void* module = LoadLibrary((LPCWSTR)fileName); 
         //compiles no mb, compiles uc, uc run fails with 126
          
         void* module = LoadLibrary((LPCSTR)fileName); 
         //compiles mb,runs mb, no uc
          
         void* module = LoadLibraryA(fileName); //note explicit A
         //compiles mb,runs mb, compiles uc,runs uc
    
     DWORD lasterror = GetLastError();//0 is ok

Today I banged my head again to 126.
I learned one thing that makes 126 happen again on top of those previous examples is chained loading of java’s virtual machine dll from my_dll. In my case my_dll needs to have jvm.dll marked as «delay loaded».
Setting is at project level:
Configuration Properties/Linker/Input/Delay Loaded Dlls
where I wrote jvm.dll;
This error is something I can repeat.

answered Jun 13, 2022 at 13:03

Tonecops's user avatar

1

// PKG Fix - index.js

const isPkg = typeof process.pkg !== 'undefined';
const c_dir = isPkg ? path.dirname(process.execPath) : __dirname;

let soname;
if (os.platform() == 'win32') {
    // Update path to load dependent dlls
    let currentPath = process.env.Path;
    let dllDirectory = path.resolve(path.join(c_dir, "win-x86_64"));
    process.env.Path = dllDirectory + path.delimiter + currentPath;
    soname = path.join(c_dir, "win-x86_64", "libvosk.dll");
} else if (os.platform() == 'darwin') {
    soname = path.join(c_dir, "lib", "osx-universal", "libvosk.dylib");
} else {
    soname = path.join(c_dir, "lib", "linux-x86_64", "libvosk.so");
}

answered Aug 9, 2022 at 20:38

Ruslan's user avatar

1

answered Feb 7, 2020 at 18:23

QuerSlider's user avatar

1

Когда я запускаю stack ghci в новом проекте, он не загружается:

$ stack new repro simple
Downloading template "simple" to create project "repro" in repro ...

(Дополнительный вывод пропущен, чтобы сделать вопрос более читаемой.)

$ cd repro/

$ stack ghci
Using main module: 1. Package `repro' component repro:exe:repro with main-is file: C:UsersmarkDesktopreprosrcMain.hs
Building all executables for `repro' once. After a successful build of all of them, only specified executables will be rebuilt.
repro> configure (exe)
Configuring repro-0.1.0.0...
repro> initial-build-steps (exe)
Configuring GHCi with the following packages: repro
GHCi, version 8.6.5: http://www.haskell.org/ghc/  :? for help
<command line>: user specified .o/.so/.DLL could not be loaded (addDLL: pthread or dependencies not loaded. (Win32 error 5))
Whilst trying to load:  (dynamic) pthread
Additional directories searched:   C:\Users\mark\AppData\Local\Programs\stack\x86_64-windows\msys2-20180531\mingw64\lib
   C:\Users\mark\AppData\Local\Programs\stack\x86_64-windows\msys2-20180531\mingw64\bin
   C://Users//mark//AppData//Local//Programs//stack//x86_64-windows//ghc-8.6.5//mingw//bin/
   C://Users//mark//AppData//Local//Programs//stack//x86_64-windows//ghc-8.6.5//mingw//bin/../lib/
   C://Users//mark//AppData//Local//Programs//stack//x86_64-windows//ghc-8.6.5//mingw//bin/../lib/gcc/x86_64-w64-mingw32/7.2.0/
   C:/Users/mark/AppData/Local/Programs/stack/x86_64-windows/ghc-8.6.5/mingw/bin/../lib/gcc/x86_64-w64-mingw32/7.2.0/
   C:/Users/mark/AppData/Local/Programs/stack/x86_64-windows/ghc-8.6.5/mingw/bin/../lib/gcc/
   C:/Users/mark/AppData/Local/Programs/stack/x86_64-windows/ghc-8.6.5/mingw/bin/../lib/gcc/x86_64-w64-mingw32/7.2.0/../../../../x86_64-w64-mingw32/lib/../lib/
   C:/Users/mark/AppData/Local/Programs/stack/x86_64-windows/ghc-8.6.5/mingw/bin/../lib/gcc/x86_64-w64-mingw32/7.2.0/../../../../lib/
   C:/Users/mark/AppData/Local/Programs/stack/x86_64-windows/ghc-8.6.5/mingw/bin/../lib/gcc/x86_64-w64-mingw32/7.2.0/../../../../x86_64-w64-mingw32/lib/
   C:/Users/mark/AppData/Local/Programs/stack/x86_64-windows/ghc-8.6.5/mingw/bin/../lib/gcc/x86_64-w64-mingw32/7.2.0/../../../
   C:Windowssystem32

Это на Windows 10 (x64). У меня другая машина с аналогичной конфигурацией ОС и версией стека, а на этой машине у меня нет проблем. Это кажется проблемой окружающей среды, но я не могу выяснить, что это такое.

Я бегаю из Git Bash , и если я бегу в него как администратор, он работает:

$ stack ghci
Using main module: 1. Package `repro' component repro:exe:repro with main-is file: C:UsersmarkDesktopreprosrcMain.hs
Building all executables for `repro' once. After a successful build of all of them, only specified executables will be rebuilt.
repro> initial-build-steps (exe)
Configuring GHCi with the following packages: repro
GHCi, version 8.6.5: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( C:UsersmarkDesktopreprosrcMain.hs, interpreted )
Ok, one module loaded.
Loaded GHCi configuration from C:\Users\mark\AppData\Local\Temp\haskell-stack-ghci\2524149e\ghci-script
*Main>

Я работаю со стеком в течение многих лет в Windows, и это первый раз, когда я должен работать как администратор, и это действительно беспокоит меня. Что может быть проблемой, и как мне это обратиться?

FWIW, это стек версии:

$ stack --version
Version 2.1.3, Git revision 0fa51b9925decd937e4a993ad90cb686f88fa282 (7739 commits) x86_64 hpack-0.31.2

Это одна и та же версия, что и у меня на другой машине, в которой проблема не появляется.

Примеры здесь копируются от бега Git Bash , но проблема такая же, если я использую cmd.

1 ответ

Лучший ответ

Благодаря Федору Соикину, я смог отследить вопрос.

Резюме

Дайте вашу учетную запись пользователя Read & execute Разрешения pthread.dll.

Детали

Я не понимал, почему эта новая машина моя выставила эту проблему, в то время как другая машина с той же ОС и в основном такая же установка не было проблем.

На тесной проверке оказалось, что другие машины не имели файл pthread.dll вообще .

У него было достаточно нескольких копий pthread.h, хотя, и я полагаю, что этого было достаточно, чтобы включить в комплекс , чтобы построить код.

Новая машина имела pthread.dll в нескольких местах, включая подкаталог C:WindowsSystem32DriverStore, что подразумевает мне, что этот файл изначально прибыл через драйвер, который использует новую машину, но старая машина не имела Отказ Он также имеет копию pthread.dll в C:WindowsSystem32, но этот файл был чрезвычайно заблокирован. Моя собственная учетная запись пользователя не имела Read или Execute или Execute и Execute в файл, но я мог бы просмотреть и изменить разрешения в режиме Administrator .

Я дал локальные пользователи group Read & execute права на файл, после чего все, кажется, работает, как это ранее сделано на моих других машинах.


9

Mark Seemann
8 Окт 2019 в 00:04

Содержание

  1. Что делать, если ошибка 126 «Не найден указанный модуль»?
  2. Причины ошибки 126
  3. Как исправить ошибку 126?
  4. Способ 1: автоматическое исправление проблем с DLL-файлами
  5. Способ 2: временно отключаем антивирус
  6. Способ 3: обновляем Microsoft NET Framework
  7. Способ 4: переустанавливаем DirectX
  8. Способ 5: сканируем системные файлы Windows
  9. Способ 6: восстанавливаем системные реестр
  10. Способ 7: делаем откат Windows
  11. Ошибка 126 не найден указанный модуль – как исправить
  12. Устранение системной ошибки 126 в установщике модулей Windows
  13. Не найден указанный модуль: «Ошибка 126» (Error 126)
  14. Причины возникновения «Ошибка 126: не найден указанный модуль» DLL
  15. Исправляем «Ошибку 126 (Error 126): не найден указанный модуль DLL» на Windows
  16. Существуют меры, при которых ваши DLL-файлы всегда будут в безопасности:
  17. «Не найден указанный модуль»: при загрузке Windows
  18. Ошибка 126 «Указанный модуль не найден»: при запуске приложения
  19. «Не найден указанный модуль, ошибка 126»: при подключении USB-накопителей
  20. Включаем службу «Доступ к НID-устройствам»

Что делать, если ошибка 126 «Не найден указанный модуль»?

Ошибки с кодами 126, реже 127, ссылаются на то, что «Не найден указанный модуль». Таким образом легко сделать вывод – в Windows 7, 8, 10 недостает какого-то файла. Это действительно часто означает отсутствие DLL-библиотеки, но не всегда. Дело может быть и в других неприятных неполадках с реестром или системой защиты и т. п. Вполне может быть, что все дело и в самой программе, которая этот сбой провоцирует. Мы поможем исправить ошибку (Error 126) своими силами, ничего особо сложного в этом нет. Однако, предупреждаем, что неправильные действия в реестре или при взаимодействии с драйверами могут вызвать негативные последствия для работы операционной системы.

Причины ошибки 126

Если отображается ошибка 126 «Не найден модуль» – можем сделать вывод о наличии одной из перечисленных ниже проблем:

  • отсутствует, не зарегистрирован или поврежден DLL-файл;
  • неправильная настройка или нарушение целостности системных файлов;
  • некорректная установка программы или она была чем-то прервана;
  • повреждение Windows вирусами;
  • сбой в системном реестре;
  • проблема в драйверах, настройке оборудования или его несовместимости с версией операционной системы.

Как исправить ошибку 126?

Мы разработали серию решений проблемы, одно из них обязано помочь, так как исправляет каждую из перечисленных проблем. Логично, что после устранения неполадки, все должно заработать правильно.

Способ 1: автоматическое исправление проблем с DLL-файлами

Есть специальная утилита, которая автоматически сканирует системные библиотеки и сравнивает их с эталоном. Если она обнаружит, что какого-то файла или нескольких, недостает, она сама их загрузит. Также происходит анализ битых, поврежденных и модифицированных файлов. Это очень удобно и быстро в сравнении с ручным способом и, что немаловажно, еще и более безопасно. На личном опыте, программа работает стабильно и не устанавливает файлы, зараженные вирусами. Однако любые манипуляции с DLL-библиотеками сложно назвать полностью безопасными.

Инструкция по устранению ошибки 126:

  1. Загружаем программу Restoro PC Repair Tool. Лучше это делать с официального сайта.
  2. Устанавливаем и запускаем софт. Нажимаем на кнопку «Начать сканирование» (Start Scan).
  3. После процедуры анализа системы кликаем по клавише «Восстановить все» (Repair All).

Важное достоинство программы – она оптимизирует компьютер, увеличивая его производительность (если в системе есть какие-то проблемы с DLL). Ее можно оставить в качестве настольного софта, так как утилита решает большой спектр проблем.

Способ 2: временно отключаем антивирус

Есть большая вероятность, что ошибка 126 спровоцирована антивирусной защитой системы. Если в момент установки программы антивирус посчитал один из компонентов угрозой и заблокировал его, он будет отсутствовать, а система писать «Не найден указанный модуль». В целом желательно отключать защиту в момент установки программ, которым доверяем.

  1. Выключаем антивирус (встроенный Защитник Windows и/или сторонний).
  2. Полностью удаляем программу через «Программы и компоненты» (пункт находится в Панели управления).
  3. Начинаем установку утилиты снова, проверив, что сейчас антивирус не работает.
  4. Проверяем результат.

Если сейчас программа заработала нормально, рекомендуем открыть антивирус и добавить в список его исключений данный софт. В противном случае со временем ошибка может вернуться, ведь антивирусная защита снова может заблокировать или удалить файл.

Важно! Для максимального результата лучше сделать полное удаление программы. Для этого можем воспользоваться iObit Uninstaller. Софт анализирует систему и ищет остатки файлов приложения, удаляя и их.

Способ 3: обновляем Microsoft NET Framework

Устаревание платформы Microsoft NET Framework нередко приводит к ошибкам с кодом 126 и 127. Благо, это просто решается, достаточно обновить среду. Если дело было в этом, все должно заработать. Скачать актуальную версию NET Framework можем с официального сайта Microsoft.

Способ 4: переустанавливаем DirectX

Очень много DLL-файлов напрямую связаны с DirectX, поэтому есть высокая вероятность, что сообщение «Не найден указанный модуль» относится к данному программному компоненту. Его легко переустановить, так как DirectX тоже распространяет Microsoft совершенно бесплатно и для любых версий, конфигураций операционной системы. С установкой проблем быть не должно, за исключением одного момента – желательно, перед началом инсталляции софта удалить старую версию DirectX.

Способ 5: сканируем системные файлы Windows

Во всех актуальных версиях Windows есть встроенный инструмент анализа системных файлов. Он часто помогает при различных проблемах с DLL-файлами.

Как запустить системные файлы:

  1. В поиск Windows вводим cmd и запускаем «Командную строку».
  2. Вводим команду sfc /scannow.
  3. Ждем завершения сканирования системы. Все ошибки должны быть исправлены автоматически, если такая возможность есть.

Способ 6: восстанавливаем системные реестр

Ошибка 126 и 127 может быть следствием скопления мусора в реестре или повреждения значений в нем. Одна проблема – вручную все перелистать и исправить просто нереально. Для этого лучше использовать специальные программы, например, Total System Care. В утилите есть все необходимое для анализа системного реестра, его оптимизации и исправления существующих проблем. Еще можем порекомендовать CCleaner. Обе программы справятся со своими задачами.

Способ 7: делаем откат Windows

Если никакие ручные способы исправления не помогают, что бывает редко, приходится обратиться к последнему методу и откатить Windows к последнему рабочему состоянию. Иногда файлы DLL могут пропадать из-за удаления программы, и вы можете столкнуться с ошибкой 126. Чтобы устранить ее, воспользуйтесь точками восстановления. Найти «Параметры восстановления» можем через поиск в Windows.

Теперь ошибка с кодом 126 больше не должна беспокоить пользователя как в Windows 7, так и 8, 10. Одна из процедур практически 100% должна исправить проблему. При этом мы не рекомендуем вручную менять DLL-файл, если удалось обнаружить в каком именно проблема. Все из-за чрезмерно высокого шанса загрузить вирус.

Источник

Ошибка 126 не найден указанный модуль – как исправить

Автор: Юрий Белоусов · Опубликовано 22.03.2017 · Обновлено 13.04.2017

Ошибка 126 не найден указанный модуль – как исправить

Если при загрузке операционной системы Windows 7 или XP или при запуске некоторых приложений на этой ОС появляется ошибка « System Error. Code: 126. Не найден указанный модуль » или же « LoadLibrary failed with error 126: Не найден указанный модуль », то вам следует сделать ознакомиться с инструкцией.

Устранение системной ошибки 126 в установщике модулей Windows

Для исправления ошибки следует:

  1. Запустить командную строку от имени администратора. Для этого нужно зайти в меню «Пуск» и вписать команду cmd . Потом правой кнопкой мыши вызвать контекстное меню и нажать «Запуск от имени администратора».
  2. Затем в появившемся окне с командной строкой следует написать следующую команду:
    Для Windows x64: COPY atio6axx.dll .dll
    Для Windows x32: COPY atioglxx.dll .dll

    (Стоит отметить, что в командной строке не работают клавиши Ctrl+C и Ctrl+V. Поэтому следует вставлять с помощью правой кнопкой мыши, если вы конечно скопировали код, а не прописали вручную).
    Затем следует нажать Enter.
  3. Когда запросит подтверждение копирования файла нужно будет написать Yes ;
  4. Затем прописать или скопировать:
    Для Windows x64: copy atio6axx.dll atiogl64.dll
    Для Windows x32: copy atioglxx.dll atiogl32.dll
  5. В завершении – перезагрузить компьютер.

Обязательно обратите внимание, что перед вводом команды путь должен быть таким:

Если вдруг пусть указан другой, то нужно сделать следующее:

  1. Убедиться, что вы запустили командную строку от имени администратора;
  2. Если путь по-прежнему неправильный, то прописать следующее:
    CD /d C:Windowssystem32
    И нажать Enter.
    А потом следовать инструкции из первой части.

P.S. Если пишет «Не удается найти указанный файл», то фиг его знает как с этим бороться. Если вдруг кто-нибудь найдет решение проблемы, буду признателен за комментарий.

Надеюсь, статья «Ошибка 126 не найден указанный модуль – как исправить» была вам полезна.

Источник

Не найден указанный модуль: «Ошибка 126» (Error 126)

Опубликовано 14.05.2022 · Обновлено 11.01.2023

«Не найден указанный модуль DLL: Ошибка 126 (Error 126)» возникает, когда операционная система не может загрузить или обработать интегральные системные настройки, необходимые для запуска определенной службы на компьютере.

Службы предназначены для того, чтобы операционная система могла выполнять определенные функции, такие как сетевые адаптеры, брандмауэр Windows, удаленный доступ и многое другое.

«Ошибка 126: не найден указанный модуль» («Error 126: The specified module could not be found») — одна из наиболее часто встречающихся ошибок на компьютерах под управлением Windows. Эта ошибка не характерна для какой-либо конкретной программы и может возникнуть при попытке запустить и/или установить что-либо.

Причины возникновения «Ошибка 126: не найден указанный модуль» DLL

Основная причина возникновения «Ошибки 126 (Error 126): не найден указанный модуль» на Windows заключается в том, что Windows не может найти файлы DLL, необходимые для запуска процесса установки, так сказать для динамического связывания и это может произойти по любой из следующих причин:

  • Файлы DLL могут отсутствовать в каталоге динамической компоновки вашей системы.
  • Необходимые файлы могли быть случайно удалены вами. DLL-файлы находятся в папке Windows на диске C и пользователи не проходят этот путь регулярно, поэтому такая возможность встречается довольно редко.

Наиболее частая причина ошибки 126 — повреждение файлов DLL, они могут быть повреждены из-за множества причин, таких как: ненормальное завершение любого процесса, принудительное закрытие задач, неправильное завершение работы системы, неудачное удаление, вредоносные программы, вирусные атаки и т.д.

  • Если файлы DLL не повреждены и не удалены из системы, проблема должна быть в реестре Windows. Все файлы DLL, присутствующие в системе, должны быть зарегистрированы в Windows, но иногда из-за некоторых ошибок в записях реестра эти файлы не регистрируются. Из-за этого файлы DLL не загружаются, когда они необходимы установщику Windows.

Исправляем «Ошибку 126 (Error 126): не найден указанный модуль DLL» на Windows

Существуют меры, при которых ваши DLL-файлы всегда будут в безопасности:

  1. Запустить проверку диска: попробуйте иногда запускать проверку диска или лучше запланировать проверку диска. Он проанализирует жесткий диск на наличие системных ошибок и повреждений файлов.
  2. Восстановление файлов вручную: просто перейдите в командную строку и выполните эту команду: SFC SCANNOW. Для выполнения этой команды потребуются права администратора. Он автоматически найдет и исправит ошибки в файлах Windows.
  3. Обновите антивирус и выполните полное сканирование системы, чтобы удалить из нее вредоносные программы и вирусы.
  4. Переустановите программное обеспечение, которое вызывает ошибку: он восстановит связанный с ним DLL файл, а также обновит реестр вашей системы.

«Не найден указанный модуль»: при загрузке Windows

При загрузке Windows, такая ошибка появляется, когда отсутствует какой-то файл, который был прописан в автозагрузку, и которого сейчас нет. Можно предположить, что его мог удалить ваш антивирус, распознав в нем вирусное ПО. Такое бывает, хоть и не часто.

  • Запустите редактор реестра: «Win+R» — regedit
  • Перейдите по пути: HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionWinlogon

  • Параметр Shell должен иметь значение explorer.exe. Если обнаружили, какое-то другое значение, тогда удалите его. Точно также нужно поступить с параметром Userinit, который должен иметь значение — C:WindowsSystem32userinit.exe
  • После выполненных действий перезагрузите компьютер.

Ошибка 126 «Указанный модуль не найден»: при запуске приложения

Если код ошибки 126 возникает при запуске приложения, как правило, достаточно просто найти рабочую версию приложения и скопировать взамен старого неработающего.

Если говорить о драйверах, то лучшим решением будет посетить сайт производителя и установить последнюю версию. Можно также, при наличии компьютера с подобным ПО, скопировать из него недостающий файл.

«Не найден указанный модуль, ошибка 126»: при подключении USB-накопителей

Есть в любой операционной системе такая служба, которая называется «Доступ к НID-устройствам». Как и любая системная служба, она серьезно влияет на работоспособность системы. Но данная служба имеет непосредственное виляние на большинство USB-устройств.

Часто бывает так, что служба может не запуститься по каким-либо причинам! Соответственно, раз эта служба не запустилась, то возникают проблемы с USB — устройствами. Особенно часто можно столкнуться с такой проблемой в ОС Мicrosoft Windows Ноme Еdition.

Выглядит проблема так: При запуске сервиса «Доступ к НID-устройствам» вылезает ошибка «Служба Доступ к НID-устройствам не запущена. Ошибка 126: не найден указанный модуль». Если такое случилось, не стоит отчаиваться, проблема вполне решаема.

Возможно, что служба просто отключена (бывает так, что служба отключается, хотя раньше она работала). Поэтому, всё что от вас требуется — включить её самостоятельно.

Включаем службу «Доступ к НID-устройствам»

  • Для этого надо войти в «Панель управления» и выбрать раздел «Службы».
  • Далее, вы увидите большой перечень служб, которые установлены на вашем компьютере. Прокрутите перечень вниз и найдите нужную службу — «Доступ к НID-устройствам».
  • Внимательно посмотрите в раздел «Тип запуска» и если надо, то переключите эту службу в режим «Авто» (просто кликните на этой службе два раза левой кнопкой мышки, установите тип в режим «Авто» и нажмите «Применить» и «Ок»). Проблема должна решиться сразу.

Однако, если всё же переключение не помогло, либо служба и так была включена, то можно провести следующие действия:

  • Открываем системную папку «Windows» и находим в ней файл Drivers.cab, который расположен в папке «i386».
  • Откройте эту папку и извлеките из неё три файла:hidserv.dll, mouclass.sys и mouhid.sys
  • Создайте на рабочем столе папку, перетащите в неё эти три файла и перезагрузите систему в «Безопасном режиме».
  • Затем войдите в системную папку «Windows» — «system32» и скопируйте туда три файла hidserv.dll, mouclass.sys и mouhid.sys.
  • Перезагрузите систему (проблема решается в 99 случаях из 100).

А чтобы с вашим компьютером возникало меньше проблем, необходимо регулярно проводить его оптимизацию и очистку системы, для этого необходимо использовать специализированные программы, которые в полной мере позаботятся о вашем компьютере!

Источник

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Add restrictions error ростелеком
  • Add migration initialcreate ошибка
  • Add apt repository error
  • Add account error java lang securityexception
  • Add a category to go live твич как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии