{"record":{"id":"cb2ebbdcf3038d32","repo":"java-native-access/jna","slug":"win32exception-from-native-getlasterror-after-loadlibraryex","errorCode":null,"errorMessage":"Win32Exception from native GetLastError after LoadLibraryEx failed","messagePattern":"Win32Exception from native GetLastError after LoadLibraryEx failed","errorType":"error_code","errorClass":"Win32Exception","httpStatus":null,"severity":"error","filePath":"contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java","lineNumber":985,"sourceCode":"\n    /**\n     * Gets the specified resource out of the specified executable file\n     *\n     * @param path\n     *            The path to the executable file\n     * @param type\n     *            The type of the resource (either a type name or type ID is\n     *            allowed)\n     * @param name\n     *            The name or ID of the resource\n     * @return The resource bytes, or null if no such resource exists.\n     * @throws IllegalStateException if the call to LockResource fails\n     */\n    public static byte[] getResource(String path, String type, String name) {\n        HMODULE target = Kernel32.INSTANCE.LoadLibraryEx(path, null, Kernel32.LOAD_LIBRARY_AS_DATAFILE);\n\n        if (target == null) {\n            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());\n        }\n\n        Win32Exception err = null;\n        Pointer start = null;\n        int length = 0;\n        byte[] results = null;\n        try {\n            Pointer t = null;\n            try {\n                t = new Pointer(Long.parseLong(type));\n            } catch (NumberFormatException e) {\n                t = new Memory(Native.WCHAR_SIZE * (type.length() + 1));\n                t.setWideString(0, type);\n            }\n\n            Pointer n = null;\n            try {\n                n = new Pointer(Long.parseLong(name));","sourceCodeStart":967,"sourceCodeEnd":1003,"githubUrl":"https://github.com/java-native-access/jna/blob/d036ad9781adad4b66693e8fa7098e4ac665e0a3/contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java#L967-L1003","documentation":"getResource(path, type, name) extracts an embedded resource from an executable/DLL by loading it with LoadLibraryEx using LOAD_LIBRARY_AS_DATAFILE. If LoadLibraryEx returns null, the wrapper throws Win32Exception with the native GetLastError code — typically ERROR_MOD_NOT_FOUND (file missing or its dependencies unreadable) or ERROR_BAD_EXE_FORMAT (not a valid PE file / 32-vs-64-bit mismatch).","triggerScenarios":"Calling Kernel32Util.getResource(path, type, name) when LoadLibraryEx(path, null, LOAD_LIBRARY_AS_DATAFILE) returns null — the file path does not exist, the file is not a valid PE image, the path is a resource DLL for the wrong architecture, or the file cannot be opened due to permissions/locking.","commonSituations":"Typo'd or relative DLL path resolved against the wrong working directory; attempting to read resources from a .NET assembly or script that is not a native PE; antivirus quarantining/locking the file; extracting icons/strings from an executable that was since updated or removed.","solutions":["Verify the file exists and is a native PE (check MZ header) before calling: new File(path).isFile().","Resolve the path to an absolute path to avoid dependence on the process working directory.","Inspect Win32Exception.getErrorCode(): 126 (ERROR_MOD_NOT_FOUND) = missing file, 193 (ERROR_BAD_EXE_FORMAT) = wrong architecture/format.","Catch Win32Exception and provide a fallback resource lookup or a clear user-facing message."],"exampleFix":"// before\nbyte[] icon = Kernel32Util.getResource(\"notepad.exe\", \"RT_GROUP_ICON\", \"APP\");\n\n// after\nPath exe = Paths.get(\"C:\\\\Windows\\\\notepad.exe\").toAbsolutePath();\nif (!Files.isRegularFile(exe)) {\n    throw new FileNotFoundException(exe.toString());\n}\nbyte[] icon;\ntry {\n    icon = Kernel32Util.getResource(exe.toString(), \"RT_GROUP_ICON\", \"APP\");\n} catch (Win32Exception e) {\n    throw new IOException(\"Cannot load resources from \" + exe + \" (code \" + e.getErrorCode() + \")\", e);\n}","handlingStrategy":"validation","validationCode":"Path p = Paths.get(path).toAbsolutePath();\nif (!Files.isRegularFile(p)) {\n    throw new FileNotFoundException(p.toString());\n}\ntry (FileChannel ch = FileChannel.open(p, StandardOpenOption.READ)) {\n    byte[] hdr = new byte[2];\n    ch.read(ByteBuffer.wrap(hdr));\n    if (hdr[0] != 'M' || hdr[1] != 'Z') {\n        throw new IOException(\"Not a PE file: \" + p);\n    }\n}","typeGuard":null,"tryCatchPattern":"try {\n    return Kernel32Util.getResource(path, type, name);\n} catch (Win32Exception e) {\n    throw new IOException(\"LoadLibraryEx failed for \" + path + \" (code \" + e.getErrorCode() + \")\", e);\n}","preventionTips":["Resolve resource DLL paths to absolute files and verify existence first.","Confirm the target is a native PE (MZ header); .NET managed-only assemblies can still load but expect mixed results.","Match bitness expectations — ERROR_BAD_EXE_FORMAT (193) means wrong architecture.","Watch for antivirus quarantine/locking of the target file."],"tags":["win32","resources","dll","jna"],"backgroundTag":"file-not-found","analyzedSha":"d036ad9781adad4b66693e8fa7098e4ac665e0a3","analyzedAt":"2026-09-12T06:50:59.239Z","contentChangedAt":"2026-09-12T06:50:59.239Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}