Microsoft MVP성태의 닷넷 이야기
VC++: 49. 소스 코드로부터 php5apache2_2.dll 생성하는 방법 [링크 복사], [링크+제목 복사],
조회: 30175
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
소스 코드로부터 php5apache2_2.dll 생성하는 방법

지난번에, PHP 환경을 소스 코드로부터 빌드하는 방법을 알아봤었습니다.

PHP 소스를 윈도우 환경에서 빌드하기
; https://www.sysnet.pe.kr/2/0/1042

그때도 언급했지만 PHP의 빌드된 버전을 다운로드한 것과 소스 코드로부터 빌드한 결과물에 상당한 차이가 있었습니다. 그중에서, 아파치의 httpd.conf에 등록해 줘야 하는 php5apache2_2.dll 파일이 누락되어 있다고 했는데요. 이제는 제법 모듈에 대한 이해도 했으니,

윈도우에서 Apache Module 컴파일 (VC++)
; https://www.sysnet.pe.kr/2/0/1051

윈도우에서 Apache Module - Content Handler 컴파일
; https://www.sysnet.pe.kr/2/0/1056

php5apache2_2.dll을 소스 코드로부터 생성하는 방법을 알아봐야겠습니다. ^^




이를 위해 우선 소스 코드를 찾아야 하는데, php-5.3.6.tar.gz을 풀어놓은 폴더들을 보니 "D:\phpbuild\php53dev\vc9\x86\php-5.3.6\sapi\apache2handler"가 바로 php5apache2_2.dll에 대한 소스 코드라고 예상되더군요. 해당 폴더에 보면, config.w32라는 파일이 있는데 아래와 같은 내용을 포함하고 있습니다.

// vim:ft=javascript
// $Id: config.w32 259731 2008-05-14 03:13:17Z auroraeosrose $

ARG_ENABLE('apache2handler', 'Build Apache 2.x handler', 'no');

if (PHP_APACHE2HANDLER != "no") {
    if (PHP_ZTS == "no") {
        WARNING("Apache2 module requires an --enable-zts build of PHP on windows");
    } else if (CHECK_HEADER_ADD_INCLUDE("httpd.h", "CFLAGS_APACHE2HANDLER", PHP_PHP_BUILD + "\\include\\apache2") &&
            CHECK_LIB("libhttpd.lib", "apache2handler", PHP_PHP_BUILD + "\\lib\\apache2") &&
            CHECK_LIB("libapr.lib", "apache2handler", PHP_PHP_BUILD + "\\lib\\apache2") &&
            CHECK_LIB("libaprutil.lib", "apache2handler", PHP_PHP_BUILD + "\\lib\\apache2")
            ) {
        SAPI('apache2handler', 'mod_php5.c sapi_apache2.c apache_config.c php_functions.c',
                'php' + PHP_VERSION + 'apache2.dll',
                '/D PHP_APACHE2_EXPORTS /I win32');
    } else {
        WARNING("Could not find apache2 libraries/headers");
    }
}

ARG_ENABLE('apache2-2handler', 'Build Apache 2.2.x handler', 'no');

if (PHP_APACHE2_2HANDLER != "no") {
    if (PHP_ZTS == "no") {
        WARNING("Apache2 module requires an --enable-zts build of PHP on windows");
    } else if (CHECK_HEADER_ADD_INCLUDE("httpd.h", "CFLAGS_APACHE2_2HANDLER", PHP_PHP_BUILD + "\\include\\apache2_2") &&
            CHECK_LIB("libhttpd.lib", "apache2_2handler", PHP_PHP_BUILD + "\\lib\\apache2_2") &&
            CHECK_LIB("libapr-1.lib", "apache2_2handler", PHP_PHP_BUILD + "\\lib\\apache2_2") &&
            CHECK_LIB("libaprutil-1.lib", "apache2_2handler", PHP_PHP_BUILD + "\\lib\\apache2_2")
            ) {
        SAPI('apache2_2handler', 'mod_php5.c sapi_apache2.c apache_config.c php_functions.c',
                'php' + PHP_VERSION + 'apache2_2.dll',
                '/D PHP_APACHE2_EXPORTS /I win32',
                'sapi\\apache2_2handler');
    } else {
        WARNING("Could not find apache2.2 libraries/headers");
    }
}

config.w32 파일이 어떻게 해석되는지는 정확히 알 수 없으나, 대충의 감각으로 보면 'apache2handler' 옵션이 설정되어 있으면 php5apache2.dll 파일이 생성되고, apache2-2handler 옵션이 설정되어 있으면 php5apache2_2.dll을 생성해 내는 것으로 보입니다. 이걸 보면서 지난번 글의 마지막에 옮겨두었던 configure --help 출력물이 생각나더군요.

D:\phpbuild\php53dev\vc9\x86\php-5.3.6>configure --help
Options that enable extensions and SAPI will accept 'yes' or 'no' as a
parameter. They also accept 'shared' as a synonym for 'yes' and request a
shared build of that module. Not all modules can be built as shared modules;
configure will display [shared] after the module name if can be built that
way.

... [생략] ...
  --with-apache-libs            Where to find Apache 1.3 libraries
  --enable-apache2filter        Build Apache 2.x filter
  --enable-apache2-2filter      Build Apache 2.2.x filter
  --enable-apache2handler       Build Apache 2.x handler
  --enable-apache2-2handler     Build Apache 2.2.x handler
  --with-apache-hooks           Build Apache 1.3.x (hooks) version of PHP
  --disable-cgi                 Build CGI version of PHP
  --disable-cli                 Build CLI version of PHP
... [생략] ...

그럴 듯하지요. ^^ 그래서, 이번에는 PHP 소스 코드 빌드 과정에서 위의 옵션을 포함해 보았습니다. (지난번에 이미 한번 빌드를 해서 환경 구축을 했으므로 그 부분은 생략합니다.)

먼저, "시작" / "Microsoft Windows SDKK v6.1" / "CMD Shell"을 실행시키고, 다음과 같이 일련의 명령을 내려 보았는데,

D:\Program Files\Microsoft SDKs\Windows\v6.1>setenv /x86 /xp /release

D:\Program Files\Microsoft SDKs\Windows\v6.1>cd /d d:\phpbuild

d:\phpbuild>.\bin\phpsdk_setvars.bat

d:\phpbuild>REM phpsdk.bat
d:\phpbuild>cd D:\phpbuild\php53dev\vc9\x86\php-5.3.6

D:\phpbuild\php53dev\vc9\x86\php-5.3.6>configure --disable-all --enable-cli --enable-apache2-2handler --enable-apache2handler
Saving configure options to config.nice.bat
Checking for cl.exe ...  <in default path>
  Detected compiler MSVC9 (Visual C++ 2008)
  Detected 32-bit compiler
...[생략]...
-------------------------------------------
|               |                         |
-------------------------------------------
| Build type    | Release                 |
| Thread Safety | Yes                     |
| Compiler      | MSVC9 (Visual C++ 2008) |
| Architecture  | x86                     |
-------------------------------------------


Type 'nmake' to build PHP

D:\phpbuild\php53dev\vc9\x86\php-5.3.6>nmake

Microsoft (R) Program Maintenance Utility Version 9.00.30729.01
Copyright (C) Microsoft Corporation.  All rights reserved.

Recreating build dirs
   Creating library Release_TS\php5ts.lib and object Release_TS\php5ts.exp
SAPI sapi\cli build complete

결과는 실망스럽게도 아파치 핸들러 관련 DLL이 전혀 생성되지 않았습니다. 혹시 위의 글을 보고, 뭐가 잘못되었는지 아시는 분이 계시다면 댓글 부탁드립니다. ^^




PHP 빌드 중에 자연스럽게 php5apache2.dll / php5apache2_2.dll 파일을 생성하는 것은 일단 포기하고, D:\phpbuild\php53dev\vc9\x86\php-5.3.6\sapi\apache2handler 폴더에 있는 파일들을 가지고 직접 빌드하기로 했습니다. 보니까, makefile은 없고 php5apache2.dsp 파일이 보여서 Visual Studio 2008로 열었습니다.

로드한 후, 빌드 설정을 다음과 같이 "Debug_TS"에서 "Release_TS"로 변경해 줍니다. 만약, "Debug_TS"로 빌드하고 싶다면 기존 PHP 모듈을 Debug 모드로 빌드해 두는 것이 좋습니다. (그래야만 Debug_TS에서의 모든 경로 설정이 자연스럽게 연결됩니다.)

how_to_build_phphandler_1.png

곧바로 빌드하면 httpd.h/apr_strings.h 헤더 파일들을 찾을 수 없다고 나옵니다.

fatal error C1083: Cannot open include file: 'httpd.h': No such file or directory   d:\phpbuild\php53dev\vc9\x86\php-5.3.6\sapi\apache2handler2\php_apache.h
fatal error C1083: Cannot open include file: 'apr_strings.h': No such file or directory d:\phpbuild\php53dev\vc9\x86\php-5.3.6\sapi\apache2handler2\php_functions.c

옛날 같으면 당황했겠지만 ^^ 아파치 소스 코드를 빌드해 본 경험으로 어디서 찾을 수 있을지 바로 감이 왔습니다. 즉, 아파치 빌드 결과물의 include 폴더에 모두 있는 파일이었으므로 (lib 폴더와 함께) 다음과 같이 복사했습니다.

how_to_build_phphandler_2.png

D:\httpd_build\Apache22\include
==> D:\phpbuild\php53dev\vc9\x86\deps\include\apache2_2

D:\httpd_build\Apache22\lib
==> D:\phpbuild\php53dev\vc9\x86\deps\lib\apache2_2

이제, Visual Studio에 헤더 및 라이브러리 파일을 찾는 경로를 알려주면 되겠군요. ^^

[그림: Include 경로 포함 - "Configuration Properties" / "C/C++" / "Additional Include Directories"]
how_to_build_phphandler_3.png

[그림: Lib 경로 포함 - "Configuration Properties" / "Linker" / "Additional Library Directories"]
how_to_build_phphandler_4.png

이렇게 설정하고 다시 빌드하면 다음과 같은 오류가 발생합니다.

fatal error LNK1181: cannot open input file 'libapr.lib'

이상하군요. 아파치 빌드 결과물에는 libapr-1.lib 파일명으로 되어 있는 것을 왜 PHP 핸들러에서는 libarp.lib로 찾는지 모르겠습니다. 일단은, 프로젝트 속성 창에서 이름을 다음과 같이 바꿔주었습니다.

[그림: Lib 파일명 변경 - "Configuration Properties" / "Linker" / "Input" / "Additional Dependencies"]
how_to_build_phphandler_5.png

이제 빌드하고 나면 정상적으로 "D:\phpbuild\php53dev\vc9\x86\php-5.3.6\Release_TS" 폴더에 php5apache2.dll 파일명으로 DLL이 생성됩니다. 기왕 하는 김에 이름도 바꿔주면 좋겠군요. 프로젝트 속성창에서 "Linker" / "Output File" 설정을 ".\..\..\Release_TS/php5apache2_2.dll"으로 바꿔 주고 다시 빌드를 했습니다.

마침내, "D:\phpbuild\php53dev\vc9\x86\php-5.3.6\Release_TS" 폴더(디버그인 경우 Debug_TS)에 php5apache2_2.dll 파일을 얻어내는 데 성공했습니다. 휴~~~ 힘들군요. ^^;




물론 테스트를 해봐야겠지요. ^^

기존에 아파치 소스 코드로부터 빌드했던 테스트 폴더인 "D:\httpd_build\Apache22" 하위에 "phpmodule"을 두고 이전에 빌드한 php 및 이 글을 통해 새롭게 얻은 php5apache2_2.dll 파일을 복사하고 테스트용 PHP를 방문하면 정상적으로 로드되는 것을 확인할 수 있습니다.

디버깅까지 한번 해볼까요? ^^

역시, 아파치 모듈 디버깅을 했던 것처럼, 이제 프로젝트의 php5apache2_2.dll 빌드 결과물에 대한 출력 폴더를 "D:\httpd_build\Apache22\phpmodule"로 설정하고 디버깅 프로세스를 httpd.exe로 지정합니다.

참고로, 디버그 모드로 php5apache2_2.dll을 빌드하는 경우, 의존성이 다음과 같습니다.

  • PHP5TS_DEBUG.DLL
  • LIBHTTPD.DLL
  • LIBAPR-1.DLL
  • LIBAPRUTIL-1.DLL

"D:\httpd_build\Apache22\bin" 폴더에 해당 DLL들이 모두 있는지 확인한 다음 "Shift + F2" 키를 누르면 정상적으로 디버깅이 진행되는 것을 확인할 수 있습니다.

PHP 페이지를 웹 브라우저를 통해서 방문할 때마다 실행되는 메서드 - 즉 핸들러를 찾아볼까요?

Apache Module 컴파일 글을 읽으셨다면 어렵지 않습니다. mod_php5.c에 있는 php5_module을 통해서,

AP_MODULE_DECLARE_DATA module php5_module = {
    STANDARD20_MODULE_STUFF,
    create_php_config,      /* create per-directory config structure */
    merge_php_config,       /* merge per-directory config structures */
    NULL,                   /* create per-server config structure */
    NULL,                   /* merge per-server config structures */
    php_dir_cmds,           /* command apr_table_t */
    php_ap2_register_hook   /* register hooks */
};

php_ap2_register_hook 함수에 handler가 지정될 것임을 알 수 있고, 이어서 sapi_apache2.c 파일의 php_ap2_register_hook 함수로부터,

void php_ap2_register_hook(apr_pool_t *p)
{
    ap_hook_pre_config(php_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
    ap_hook_post_config(php_apache_server_startup, NULL, NULL, APR_HOOK_MIDDLE);
    ap_hook_handler(php_handler, NULL, NULL, APR_HOOK_MIDDLE);
    ap_hook_child_init(php_apache_child_init, NULL, NULL, APR_HOOK_MIDDLE);
}

ap_hook_handler 함수 호출을 통해 php_handler가 우리가 찾던 PHP 웹 페이지 방문 시 실행되는 함수임을 알 수 있고, BP(BreakPoint)를 걸어서 확인할 수 있습니다. ^^

how_to_build_phphandler_6.png

첨부한 파일은 위와 같은 과정을 거쳐 생성된 프로젝트를 포함합니다.



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/27/2021]

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

비밀번호

댓글 작성자
 




... [121]  122  123  124  125  126  127  128  129  130  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
10899정성태2/17/201623352개발 환경 구성: 282. kernel32.dll, kernel32legacy.dll, api-ms-win-core-sysinfo-l1-2-0.dll [1]
10898정성태2/17/201621810.NET Framework: 547. PerformanceCounter의 InstanceName 지정 시 주의 사항파일 다운로드1
10897정성태2/17/201621201디버깅 기술: 76. windbg 분석 사례 - 닷넷 프로파일러의 GC 콜백 부하
10896정성태2/17/201622330오류 유형: 320. FATAL: 28000: no pg_hba.conf entry for host "fe80::1970:8120:695:a41e%12"
10895정성태2/17/201621122.NET Framework: 546. System.AppDomain으로부터 .NET Profiler의 AppDomainID 구하는 방법 [1]
10894정성태2/17/201621843오류 유형: 319. Visual Studio에서 찾기는 성공하지만 해당 소스 코드 정보가 보이지 않는 경우
10893정성태2/16/201620511.NET Framework: 545. 닷넷 - 특정 클래스가 로드되었는지 여부를 알 수 있을까? - 두 번째 이야기
10892정성태2/16/201621106오류 유형: 318. 탐색기에서 폴더 생성/삭제 시 몇 초 동안 멈추는 현상
10891정성태2/16/201624131VC++: 95. 내 CPU가 MPX/SGX를 지원할까요? [1]
10890정성태2/15/201624022.NET Framework: 544. C# 5의 Caller Info를 .NET 4.5 미만의 응용 프로그램에 적용하는 방법 [5]
10889정성태2/14/201620310.NET Framework: 543. C++의 inline asm 사용을 .NET으로 포팅하는 방법 - 두 번째 이야기파일 다운로드1
10888정성태2/14/201618644.NET Framework: 542. 닷넷 - 특정 클래스가 로드되었는지 여부를 알 수 있을까?
10887정성태2/3/201619323VC++: 94. MPX(Memory Protection Extensions) 테스트파일 다운로드1
10886정성태2/3/201620542개발 환경 구성: 281. Intel MPX Runtime Driver 수동 설치
10885정성태2/2/201620244오류 유형: 317. Sybase.Data.AseClient.AseException: The command has timed out.
10884정성태1/11/201621451개발 환경 구성: 280. 닷넷에서 SAP Adaptive Server Enterprise 데이터베이스 사용파일 다운로드1
10882정성태1/6/201620757Windows: 113. 윈도우의 2179, 26143, 47001 TCP 포트 사용 [1]
10881정성태1/3/201622184오류 유형: 316. 윈도우 10 - 바탕/돋음 체가 사라져 한글이 깨지는 현상 [2]
10880정성태12/16/201519890오류 유형: 315. 닷넷 프로파일러의 오류 코드 정보
10879정성태12/16/201521816오류 유형: 314. Error : DEP0700 : Registration of the app failed. error 0x80070005
10878정성태12/9/201524855디버깅 기술: 75. UWP(유니버설 윈도우 플랫폼) 앱에서 global::System.Diagnostics.Debugger.Break 예외 발생 시 대응 방법
10877정성태12/9/201529291VC++: 93. std::thread 사용 시 R6010 오류 [2]
10876정성태11/26/201525355.NET Framework: 541. SignedXml을 이용한 ds:Signature만드는 방법 [3]파일 다운로드1
10875정성태11/26/201530334개발 환경 구성: 279. signtool.exe의 다중 서명 기능 [2]
10874정성태11/26/201526349개발 환경 구성: 278. 인증서와 인증서를 이용한 코드 사인의 해시 구분
10873정성태11/25/201525456.NET Framework: 540. C# - 부동 소수 계산 왜 이렇게 나오죠? (2) [3]파일 다운로드1
... [121]  122  123  124  125  126  127  128  129  130  131  132  133  134  135  ...