Skip to content

Instantly share code, notes, and snippets.

@RGBA-CRT
Created July 7, 2024 15:55
Show Gist options
  • Save RGBA-CRT/f46206e6568334a7b1ae4a31461b0193 to your computer and use it in GitHub Desktop.
Save RGBA-CRT/f46206e6568334a7b1ae4a31461b0193 to your computer and use it in GitHub Desktop.
小さなEXEを作るテスト(2KB~)
i686-w64-mingw32-gcc -march=pentium -nostdlib -nodefaultlibs -fno-ident -fno-asynchronous-unwind-tables -nostartfiles tellpath.c -c -o tellpath.o
windres tellpath.rc -o res.o
ld tellpath.o res.o -olauncher.exe -T smallexe.lds -lkernel32 -luser32 --subsystem windows
strip -R .reloc launcher.exe
copy launcher.exe ..\launcher.exe /Y

note

2KBぐらいEXEファイルを作るテスト libcに頼らない、WindowsAPIを直接たたく小さいツール向け

point

gcc option

  • -nostdlib -nodefaultlibs -nostartfiles: libc, mingw標準のあれこれをつけない
  • -fno-ident: ファイル内に
  • -fno-asynchronous-unwind-tables: eh_handlerとかを作らない?

strip

  • -R .reloc: relocセクションを削除。小さいプログラムならいらないでしょう。

ld script

  • .rdataと.textのマージ
    • Windowsではセクションがnbyteの倍数でないとロードされない制約がある。
    • .rdataセクションを作られると、たった数バイトの文字列などのために結構なpaddingが挿入される
    • リンカスクリプトにより.textセクションに.rdataをマージする。
    • MSVCならリンカオプションで何とかなるが、gccだとリンカスクリプトを書く必要があった。
/* linker script for 2KB EXE / no libc */
/* ref: https://gist.github.com/pts/9ef2b1036d0b42508327559eeb2e0eb5 */
OUTPUT_FORMAT(pei-i386)
SEARCH_DIR("/usr/i686-pc-msys/lib"); SEARCH_DIR("/usr/lib"); SEARCH_DIR("/usr/lib/w32api");
SECTIONS {
/* Make the virtual address and file offset synced if the alignment is
* lower than the target page size.
*/
. = SIZEOF_HEADERS;
. = ALIGN(__section_alignment__);
.text __image_base__ + (__section_alignment__ < 0x1000 ?
. : __section_alignment__) : {
*(.text) *(SORT(.text$*)) *(.text.*) *(.gnu.linkonce.t.*) *(.glue_7t)
*(.glue_7)
*(.rdata)
*(SORT(.rdata$*))
}
.idata BLOCK(__section_alignment__) : { /* This is pure magic. */
SORT(*)(.idata$2)
SORT(*)(.idata$3)
/* These zeroes mark the end of the import list. */
LONG (0); LONG (0); LONG (0); LONG (0); LONG (0);
SORT(*)(.idata$4)
__IAT_start__ = .;
SORT(*)(.idata$5)
__IAT_end__ = .;
SORT(*)(.idata$6)
SORT(*)(.idata$7)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment