Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션

아래의 글에,

How can I try to escape the disease-ridden hot-tubs known as the TEMP and Downloads directories?
; https://devblogs.microsoft.com/oldnewthing/20230328-00/?p=107978

새로운 옵션이 소개됐군요. ^^

/DEPENDENTLOADFLAG (Set default dependent load flags)
; https://learn.microsoft.com/en-us/cpp/build/reference/dependentloadflag

이 옵션은 LoadLibraryEx의 dwFlags 인자와 동일한 값을 취하고, 그 역할도 같습니다. 단지 차이점이라면, LoadLibraryEx는 사용자가 직접 호출하는 코드에 flags를 지정하게 되는 반면, /DEPENDENTLOADFLAG는 정적으로 링크된 DLL들에 대해 자동으로 적용된다는 점입니다.

일반적으로는 DLL은 다음의 문서에 따라,

Dynamic-link library search order
; https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-search-order

제법 복잡한 규칙으로 찾게 됩니다. 자세한 것은 저 문서를 읽어보시고 여기서는 ^^ 저 옵션을 간단한 예제로 테스트해 보겠습니다.




Visual Studio로 C/C++ Console Application과 Dynamic-Link Library 유형의 프로젝트를 각각 생성한 다음, DLL 프로젝트에는 다음과 같이 테스트용 함수를 하나 추가하고,

// Dll1.h

#pragma once

#ifdef DLL1LIB_EXPORTS
#define DLL1LIBRARY_API __declspec(dllexport)
#else
#define DLL1LIBRARY_API __declspec(dllimport)
#endif

extern "C" DLL1LIBRARY_API void test_func();

// pch.cpp

#include "pch.h"
#include "Dll1.h"
#include <stdio.h>

void DLL1LIBRARY_API test_func()
{
    printf("test_func");
}

Console Application에서는 위의 함수를 사용하는 코드를 다음과 같이 넣어둡니다.

#include <iostream>

#include "..\\Dll1\\Dll1.h"
#pragma comment(lib, "..\\x64\\debug\\Dll1.lib")

int main()
{
    std::cout << "Hello World!\n";

    test_func();
}

빌드 하면 ./x64/Debug/ 디렉터리에 각각 다음과 같은 파일들이 생성되고,

ConsoleApplication1.exe
Dll1.dll
...[필요 없는 파일 생략]...

당연히 저 디렉터리에서 실행하면 화면에는 Hello World와 test_func가 출력됩니다. 자, 그럼 여기서 Dll1.dll 파일을 그 부모 디렉터리로 이동한 다음, 그 x64 디렉터리에서 ConsoleApplication1.exe를 실행해 보면 어떻게 될까요?

C:\ConsoleApplication1\x64> dir /b /s
C:\ConsoleApplication1\x64\Dll1.dll
C:\ConsoleApplication1\x64\Debug\ConsoleApplication1.exe
...[필요 없는 파일 생략]...

C:\ConsoleApplication1\x64> .\Debug\ConsoleApplication1.exe

ConsoleApplication1.exe가 위치한 디렉터리에 Dll1.dll 파일이 없는데도 잘 실행이 될 것입니다. 왜냐하면, "Dynamic-link library search order" 문서에 나오듯이 "Current Directory"에서도, 즉 해당 응용 프로그램을 실행한 경로에서도 dll을 찾기 때문입니다.

이제 약간씩 변형을 줘볼까요? ^^ 우선, DEPENDENTLOADFLAG 옵션으로 0xa00 값을 줄 텐데요,

// Linker / Command Line의 "Additional Options"에 명시

/DEPENDENTLOADFLAG:0xa00

문서에 0xa00은 다음의 2개 플래그를 OR 연산한 것입니다.

LOAD_LIBRARY_SEARCH_APPLICATION_DIR 0x00000200
LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800

그러니까, DLL을 c:\windows\system32 디렉터리와 exe 파일이 있는 디렉터리에서만 찾으라는 의미입니다. 이렇게 빌드하고 다시 위와 같은 상황으로 실행하면 이번에는 다음과 같은 오류가 발생합니다.

ConsoleApplication1.exe - System Error
The code execution cannot proceed because Dll1.dll was not found. Reinstalling the program may fix this problem. 

또한 이벤트 로그에는 다음과 같은 "정보" 항목이 남습니다.

Log Name:      System
Source:        Application Popup
...[생략]...
Event ID:      26
Task Category: None
Level:         Information
User:          SYSTEM
Description:
Application popup: ConsoleApplication1.exe - System Error : The code execution cannot proceed because Dll1.dll was not found. Reinstalling the program may fix this problem. 

왜냐하면, Dll1.dll 파일이 exe와 같은 디렉터리이거나, system32에만 있어야 하기 때문입니다. 대충 느낌이 오시죠? ^^ 그렇다면, 다음의 옵션(LOAD_LIBRARY_SEARCH_SYSTEM32)으로 주고 빌드하면 어떻게 될까요?

/DEPENDENTLOADFLAG:0x800

그럼 dll 파일을 오직 system32 디렉터리에서만 찾기 때문에 exe와 dll 파일이 같은 디렉터리에 있어도 실행되지 않습니다. 따라서 위의 옵션을 주었다면 의존하는 dll을 모두 system32로 복사해야만 합니다.




해보는 김에, 혹시 LOAD_LIBRARY_SEARCH_APPLICATION_DIR만 주면 어떻게 될까요?

/DEPENDENTLOADFLAG:0x200

현재 예제에서는 Visual C++ Debug 빌드를 했기 때문에 다음의 DLL들에 대한 의존성이 있습니다.

msvcp140d.dll
msvcp140_1d.dll
ucrtbased.dll
vcruntime140d.dll
vcruntime140_1d.dll

Visual Studio를 설치한 경우 위의 DLL들은 모두 c:\windows\system32 디렉터리에 있기 때문에 LOAD_LIBRARY_SEARCH_APPLICATION_DIR 옵션만으로 빌드하게 되면 위의 DLL들을 찾을 수 없어 System Error가 발생합니다. 따라서 해당 DLL들을 exe와 같은 디렉터리에 복사해,

C:\ConsoleApplication1\x64\Debug> dir /b
ConsoleApplication1.exe
Dll1.dll
msvcp140d.dll
msvcp140_1d.dll
ucrtbased.dll
vcruntime140d.dll
vcruntime140_1d.dll
...[필요 없는 파일 생략]...

실행하면 정상적으로 구동됩니다. 여기서 재미있는 것은, windows의 시스템 DLL(예를 들어, combase.dll, gdi32.dll, imm32.dll 등)은 이전처럼 system32 디렉터리에서 로드한다는 것입니다. 다시 말해 LOAD_LIBRARY_SEARCH_APPLICATION_DIR 옵션을 줘도 시스템 DLL들은 예외인 것입니다. (사실, 편의상 예외로 할 수밖에 없었을 것입니다. ^^)




비록 이 옵션의 지원은 Windows 10 Version 1607부터지만 개발자에게 있어 지금도 충분한 의미가 있습니다. 위의 설명을 이해하셨다면 눈치채셨을 텐데요, ^^ 보통, 개발된 응용 프로그램을 다른 PC에서 실행할 때 의존성 문제로 고생하는 경우가 있습니다. 바로 그럴 때, 저 옵션을 주고 실행해 보면 되는 것입니다. 최종적으로 실행이 잘 되면, 그 상태의 출력 디렉터리를 xcopy로 복사해 배포하면 끝입니다.

마지막으로 유의해야 할 점은, 저 옵션은 정적 링크된 DLL에 대해서만 통용된다는 점입니다. 코드상에서 LoadLibrary로 DLL 로딩을 시도하면, 그에 대해서는 "Dynamic-link library search order" 문서의 규칙을 적용받습니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/29/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2025-03-15 08시09분
Making sure that a DLL loads only from your application directory
; https://devblogs.microsoft.com/oldnewthing/20250313-00/?p=110963
정성태

... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11224정성태6/13/201718145.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
11223정성태6/12/201716828개발 환경 구성: 318. WCF Service Application과 WCFTestClient.exe
11222정성태6/10/201720552오류 유형: 399. WCF - A property with the name 'UriTemplateMatchResults' already exists.파일 다운로드1
11221정성태6/10/201717519오류 유형: 398. Fakes - Assembly 'Jennifer5.Fakes' with identity '[...].Fakes, [...]' uses '[...]' which has a higher version than referenced assembly '[...]' with identity '[...]'
11220정성태6/10/201722908.NET Framework: 660. Shallow Copy와 Deep Copy [1]파일 다운로드2
11219정성태6/7/201718217.NET Framework: 659. 닷넷 - TypeForwardedFrom / TypeForwardedTo 특성의 사용법
11218정성태6/1/201721019개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
11217정성태6/1/201716914오류 유형: 397. initerrlog: Could not open error log file 'C:\...\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'
11216정성태6/1/201719020오류 유형: 396. Activation context generation failed
11215정성태6/1/201719955오류 유형: 395. 관리 콘솔을 실행하면 "This app has been blocked for your protection" 오류 발생 [1]
11214정성태6/1/201717697오류 유형: 394. MSDTC 서비스 시작 시 -1073737712(0xC0001010) 오류와 함께 종료되는 문제 [1]
11213정성태5/26/201722477오류 유형: 393. TFS - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
11212정성태5/26/201721816오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201720855오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201721299기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201768219Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201727944오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
11207정성태5/24/201728253Windows: 142. Windows 10의 복구 콘솔로 부팅하는 방법
11206정성태5/24/201721547오류 유형: 389. DISM.exe - The specified image in the specified wim is already mounted for read/write access.
11205정성태5/24/201721269.NET Framework: 658. C#의 tail call 구현은? [1]
11204정성태5/22/201730805개발 환경 구성: 316. 간단하게 살펴보는 Docker for Windows [7]
11203정성태5/19/201718738오류 유형: 388. docker - Host does not exist: "default"
11202정성태5/19/201719809오류 유형: 387. WPF - There is no registered CultureInfo with the IetfLanguageTag 'ug'.
11201정성태5/16/201722552오류 유형: 386. WPF - .NET 3.5 이하에서 TextBox에 한글 입력 시 TextChanged 이벤트의 비정상 종료 문제 [1]파일 다운로드1
11200정성태5/16/201719331오류 유형: 385. WPF - 폰트가 없어 System.IO.FileNotFoundException 예외가 발생하는 경우
11199정성태5/16/201721155.NET Framework: 657. CultureInfo.GetCultures가 반환하는 값
... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...