Skip to content

Instantly share code, notes, and snippets.

@snipsnipsnip
Created February 2, 2015 00:37
Show Gist options
  • Save snipsnipsnip/1df1c06cdf4ed4d1fb46 to your computer and use it in GitHub Desktop.
Save snipsnipsnip/1df1c06cdf4ed4d1fb46 to your computer and use it in GitHub Desktop.
引数で渡された Windows 実行形式ファイルの Machine タイプを判別する
//
// 引数で渡された Windows 実行形式ファイルの Machine タイプを判別する
// http://dsas.blog.klab.org/archives/51752824.html
//
#if !defined(UNICODE)
#define UNICODE
#define _UNICODE
#endif
#include <windows.h>
#include <stdio.h>
#include <sys/stat.h>
#pragma comment(lib, "user32.lib")
// IMAGE_FILE_HEADER から Machine タイプを取得
int MyCheckMachineType(LPCWSTR pszFileName)
{
FILE *fp;
struct _stat st;
IMAGE_DOS_HEADER idh;
IMAGE_NT_HEADERS inh;
if (_wstat(pszFileName, &st) < 0 ||
_wfopen_s(&fp, pszFileName, L"rb") != 0) {
return -1;
}
if (fread(&idh, sizeof(IMAGE_DOS_HEADER), 1, fp) < 1 ||
idh.e_magic != IMAGE_DOS_SIGNATURE || // "MZ"
idh.e_lfanew <= 0 || idh.e_lfanew >= st.st_size) {
fclose(fp);
return -2;
}
if (fseek(fp, idh.e_lfanew, SEEK_SET) != 0 ||
fread(&inh, sizeof(IMAGE_NT_HEADERS), 1, fp) < 1 ||
inh.Signature != IMAGE_NT_SIGNATURE) { // "PE\0\0"
fclose(fp);
return -3;
}
fclose(fp);
switch (inh.FileHeader.Machine) {
case IMAGE_FILE_MACHINE_I386:
return 0;
case IMAGE_FILE_MACHINE_AMD64:
return 1;
case IMAGE_FILE_MACHINE_IA64:
return 2;
}
return 3; // Unknown
}
// 現プロセスが WOW64 下で実行中のプロセスか
BOOL MyIsWow64Process()
{
typedef BOOL (WINAPI *DEC_ISWOW64PROCESS)(HANDLE, BOOL*);
BOOL bWow64Process = FALSE;
DEC_ISWOW64PROCESS pIsWow64Process = (DEC_ISWOW64PROCESS)
GetProcAddress(GetModuleHandle(L"Kernel32.dll"),"IsWow64Process");
if (!pIsWow64Process ||
!pIsWow64Process(GetCurrentProcess(), &bWow64Process)) {
return FALSE;
}
return bWow64Process;
}
int APIENTRY wWinMain(HINSTANCE hInst, HINSTANCE hPrevInst,
LPWSTR lpCmdLine, int nCmdShow)
{
int sts;
WCHAR *pName;
WCHAR *m[] = { L"x86", L"x64", L"IA64", L"Unknown"};
WCHAR *e[] = { L"broken?", L"not executable", L"open error"};
#ifdef WIN32
if (MyIsWow64Process()) {
MessageBox(NULL,
L"WOW64 によるリダイレクトの影響を避けるために\n" \
L"Windows x64 環境では x64 版を使用して下さい",
L"Warning", MB_OK);
}
#endif
if (__argc < 2) {
return 0;
}
sts = MyCheckMachineType(__wargv[1]);
pName = wcsrchr(__wargv[1], L'\\') + 1;
if (sts >= 0 && sts <= 3) {
MessageBox(NULL, m[sts], pName, MB_ICONINFORMATION|MB_TOPMOST);
} else {
MessageBox(NULL, e[sts+3], pName, MB_TOPMOST);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment