/* * TCCPE.C - PE file output for the Tiny C Compiler * * Copyright (c) 2005-2007 grischka * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef TCC_TARGET_PE #define ST_FN static #define ST_DATA static #define PUB_FN #ifndef _WIN32 #define stricmp strcasecmp #define strnicmp strncasecmp #endif #ifndef MAX_PATH #define MAX_PATH 260 #endif #define PE_MERGE_DATA // #define PE_PRINT_SECTIONS /* ----------------------------------------------------------- */ #ifndef IMAGE_NT_SIGNATURE /* ----------------------------------------------------------- */ /* definitions below are from winnt.h */ typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned long DWORD; #pragma pack(push, 1) typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */ WORD e_magic; /* Magic number */ WORD e_cblp; /* Bytes on last page of file */ WORD e_cp; /* Pages in file */ WORD e_crlc; /* Relocations */ WORD e_cparhdr; /* Size of header in paragraphs */ WORD e_minalloc; /* Minimum extra paragraphs needed */ WORD e_maxalloc; /* Maximum extra paragraphs needed */ WORD e_ss; /* Initial (relative) SS value */ WORD e_sp; /* Initial SP value */ WORD e_csum; /* Checksum */ WORD e_ip; /* Initial IP value */ WORD e_cs; /* Initial (relative) CS value */ WORD e_lfarlc; /* File address of relocation table */ WORD e_ovno; /* Overlay number */ WORD e_res[4]; /* Reserved words */ WORD e_oemid; /* OEM identifier (for e_oeminfo) */ WORD e_oeminfo; /* OEM information; e_oemid specific */ WORD e_res2[10]; /* Reserved words */ DWORD e_lfanew; /* File address of new exe header */ } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */ #define SIZE_OF_NT_SIGNATURE 4 typedef struct _IMAGE_FILE_HEADER { WORD Machine; WORD NumberOfSections; DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; WORD Characteristics; } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; #define IMAGE_SIZEOF_FILE_HEADER 20 typedef struct _IMAGE_DATA_DIRECTORY { DWORD VirtualAddress; DWORD Size; } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; typedef struct _IMAGE_OPTIONAL_HEADER { /* Standard fields. */ WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; DWORD BaseOfData; /* NT additional fields. */ DWORD ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; DWORD SizeOfStackReserve; DWORD SizeOfStackCommit; DWORD SizeOfHeapReserve; DWORD SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[16]; } IMAGE_OPTIONAL_HEADER, *PIMAGE_OPTIONAL_HEADER; #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */ #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */ #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */ #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */ #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */ #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */ #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */ /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */ #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */ #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */ #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */ #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */ #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */ #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */ #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */ #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */ /* Section header format. */ #define IMAGE_SIZEOF_SHORT_NAME 8 typedef struct _IMAGE_SECTION_HEADER { BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; union { DWORD PhysicalAddress; DWORD VirtualSize; } Misc; DWORD VirtualAddress; DWORD SizeOfRawData; DWORD PointerToRawData; DWORD PointerToRelocations; DWORD PointerToLinenumbers; WORD NumberOfRelocations; WORD NumberOfLinenumbers; DWORD Characteristics; } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; #define IMAGE_SIZEOF_SECTION_HEADER 40 typedef struct _IMAGE_BASE_RELOCATION { DWORD VirtualAddress; DWORD SizeOfBlock; // WORD TypeOffset[1]; } IMAGE_BASE_RELOCATION; #define IMAGE_SIZEOF_BASE_RELOCATION 8 #define IMAGE_REL_BASED_ABSOLUTE 0 #define IMAGE_REL_BASED_HIGH 1 #define IMAGE_REL_BASED_LOW 2 #define IMAGE_REL_BASED_HIGHLOW 3 #define IMAGE_REL_BASED_HIGHADJ 4 #define IMAGE_REL_BASED_MIPS_JMPADDR 5 #define IMAGE_REL_BASED_SECTION 6 #define IMAGE_REL_BASED_REL32 7 #pragma pack(pop) /* ----------------------------------------------------------- */ #endif /* ndef IMAGE_NT_SIGNATURE */ /* ----------------------------------------------------------- */ #pragma pack(push, 1) struct pe_header { IMAGE_DOS_HEADER doshdr; BYTE dosstub[0x40]; DWORD nt_sig; IMAGE_FILE_HEADER filehdr; IMAGE_OPTIONAL_HEADER opthdr; }; struct pe_import_header { DWORD first_entry; DWORD time_date; DWORD forwarder; DWORD lib_name_offset; DWORD first_thunk; }; struct pe_export_header { DWORD Characteristics; DWORD TimeDateStamp; DWORD Version; DWORD Name; DWORD Base; DWORD NumberOfFunctions; DWORD NumberOfNames; DWORD AddressOfFunctions; DWORD AddressOfNames; DWORD AddressOfNameOrdinals; }; struct pe_reloc_header { DWORD offset; DWORD size; }; struct pe_rsrc_header { struct _IMAGE_FILE_HEADER filehdr; struct _IMAGE_SECTION_HEADER sectionhdr; }; struct pe_rsrc_reloc { DWORD offset; DWORD size; WORD type; }; #pragma pack(pop) /* ----------------------------------------------------------- */ ST_DATA struct pe_header pe_header = { { /* IMAGE_DOS_HEADER doshdr */ 0x5A4D, /*WORD e_magic; Magic number */ 0x0090, /*WORD e_cblp; Bytes on last page of file */ 0x0003, /*WORD e_cp; Pages in file */ 0x0000, /*WORD e_crlc; Relocations */ 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */ 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */ 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */ 0x0000, /*WORD e_ss; Initial (relative) SS value */ 0x00B8, /*WORD e_sp; Initial SP value */ 0x0000, /*WORD e_csum; Checksum */ 0x0000, /*WORD e_ip; Initial IP value */ 0x0000, /*WORD e_cs; Initial (relative) CS value */ 0x0040, /*WORD e_lfarlc; File address of relocation table */ 0x0000, /*WORD e_ovno; Overlay number */ {0,0,0,0}, /*WORD e_res[4]; Reserved words */ 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */ 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */ {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */ 0x00000080 /*DWORD e_lfanew; File address of new exe header */ },{ /* BYTE dosstub[0x40] */ /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */ 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68, 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f, 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20, 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00, }, 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */ { /* IMAGE_FILE_HEADER filehdr */ 0x014C, /*WORD Machine; */ 0x0003, /*WORD NumberOfSections; */ 0x00000000, /*DWORD TimeDateStamp; */ 0x00000000, /*DWORD PointerToSymbolTable; */ 0x00000000, /*DWORD NumberOfSymbols; */ 0x00E0, /*WORD SizeOfOptionalHeader; */ 0x030F /*WORD Characteristics; */ },{ /* IMAGE_OPTIONAL_HEADER opthdr */ /* Standard fields. */ 0x010B, /*WORD Magic; */ 0x06, /*BYTE MajorLinkerVersion; */ 0x00, /*BYTE MinorLinkerVersion; */ 0x00000000, /*DWORD SizeOfCode; */ 0x00000000, /*DWORD SizeOfInitializedData; */ 0x00000000, /*DWORD SizeOfUninitializedData; */ 0x00000000, /*DWORD AddressOfEntryPoint; */ 0x00000000, /*DWORD BaseOfCode; */ 0x00000000, /*DWORD BaseOfData; */ /* NT additional fields. */ 0x00400000, /*DWORD ImageBase; */ 0x00001000, /*DWORD SectionAlignment; */ 0x00000200, /*DWORD FileAlignment; */ 0x0004, /*WORD MajorOperatingSystemVersion; */ 0x0000, /*WORD MinorOperatingSystemVersion; */ 0x0000, /*WORD MajorImageVersion; */ 0x0000, /*WORD MinorImageVersion; */ 0x0004, /*WORD MajorSubsystemVersion; */ 0x0000, /*WORD MinorSubsystemVersion; */ 0x00000000, /*DWORD Win32VersionValue; */ 0x00000000, /*DWORD SizeOfImage; */ 0x00000200, /*DWORD SizeOfHeaders; */ 0x00000000, /*DWORD CheckSum; */ 0x0002, /*WORD Subsystem; */ 0x0000, /*WORD DllCharacteristics; */ 0x00100000, /*DWORD SizeOfStackReserve; */ 0x00001000, /*DWORD SizeOfStackCommit; */ 0x00100000, /*DWORD SizeOfHeapReserve; */ 0x00001000, /*DWORD SizeOfHeapCommit; */ 0x00000000, /*DWORD LoaderFlags; */ 0x00000010, /*DWORD NumberOfRvaAndSizes; */ /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */ {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}} }}; /* ------------------------------------------------------------- */ /* internal temporary structures */ /* #define IMAGE_SCN_CNT_CODE 0x00000020 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000 #define IMAGE_SCN_MEM_SHARED 0x10000000 #define IMAGE_SCN_MEM_EXECUTE 0x20000000 #define IMAGE_SCN_MEM_READ 0x40000000 #define IMAGE_SCN_MEM_WRITE 0x80000000 */ enum { sec_text = 0, sec_data , sec_bss , sec_idata , sec_other , sec_rsrc , sec_stab , sec_reloc , sec_last }; ST_DATA DWORD pe_sec_flags[] = { 0x60000020, /* ".text" , */ 0xC0000040, /* ".data" , */ 0xC0000080, /* ".bss" , */ 0x40000040, /* ".idata" , */ 0xE0000060, /* < other > , */ 0x40000040, /* ".rsrc" , */ 0x42000802, /* ".stab" , */ 0x42000040, /* ".reloc" , */ }; struct section_info { int cls, ord; char name[32]; DWORD sh_addr; DWORD sh_size; DWORD sh_flags; unsigned char *data; DWORD data_size; IMAGE_SECTION_HEADER ish; }; struct import_symbol { int sym_index; int iat_index; int thk_offset; }; struct pe_import_info { int dll_index; int sym_count; struct import_symbol **symbols; }; struct pe_info { TCCState *s1; Section *reloc; Section *thunk; const char *filename; int type; DWORD sizeofheaders; DWORD imagebase; DWORD start_addr; DWORD imp_offs; DWORD imp_size; DWORD iat_offs; DWORD iat_size; DWORD exp_offs; DWORD exp_size; struct section_info *sec_info; int sec_count; struct pe_import_info **imp_info; int imp_count; }; /* ------------------------------------------------------------- */ #define PE_NUL 0 #define PE_DLL 1 #define PE_GUI 2 #define PE_EXE 3 void error_noabort(const char *, ...); #ifdef _WIN32 void dbg_printf (const char *fmt, ...) { char buffer[4000]; va_list arg; int x; va_start(arg, fmt); x = vsprintf (buffer, fmt, arg); strcpy(buffer+x, "\n"); OutputDebugString(buffer); } #endif /* --------------------------------------------*/ ST_FN const char* get_alt_symbol(char *buffer, const char *symbol) { const char *p; p = strrchr(symbol, '@'); if (p && isnum(p[1]) && symbol[0] == '_') { /* stdcall decor */ strcpy(buffer, symbol+1)[p-symbol-1] = 0; } else if (symbol[0] != '_') { /* try non-ansi function */ buffer[0] = '_', strcpy(buffer + 1, symbol); } else if (0 == memcmp(symbol, "__imp__", 7)) { /* mingw 2.0 */ strcpy(buffer, symbol + 6); } else if (0 == memcmp(symbol, "_imp___", 7)) { /* mingw 3.7 */ strcpy(buffer, symbol + 6); } else { return symbol; } return buffer; } ST_FN int pe_find_import(TCCState * s1, const char *symbol) { char buffer[200]; const char *s; int sym_index, n = 0; do { s = n ? get_alt_symbol(buffer, symbol) : symbol; sym_index = find_elf_sym(s1->dynsymtab_section, s); // printf("find %d %s\n", sym_index, s); } while (0 == sym_index && ++n < 2); return sym_index; } #if defined _WIN32 || defined __CYGWIN__ #ifdef __CYGWIN__ # include # define LoadLibrary(s) dlopen(s, RTLD_NOW) # define GetProcAddress(h,s) dlsym(h, s) #else # define dlclose(h) FreeLibrary(h) #endif /* for the -run option: dynamically load symbol from dll */ void *resolve_sym(struct TCCState *s1, const char *symbol, int type) { char buffer[100]; int sym_index, dll_index; void *addr, **m; DLLReference *dllref; sym_index = pe_find_import(s1, symbol); if (0 == sym_index) return NULL; dll_index = ((Elf32_Sym *)s1->dynsymtab_section->data + sym_index)->st_value; dllref = s1->loaded_dlls[dll_index-1]; if ( !dllref->handle ) { dllref->handle = LoadLibrary(dllref->name); } addr = GetProcAddress(dllref->handle, symbol); if (NULL == addr) addr = GetProcAddress(dllref->handle, get_alt_symbol(buffer, symbol)); if (addr && STT_OBJECT == type) { /* need to return a pointer to the address for data objects */ m = (void**)tcc_malloc(sizeof addr), *m = addr, addr = m; #ifdef MEM_DEBUG /* yep, we don't free it */ mem_cur_size -= sizeof (void*); #endif } return addr; } #endif /*----------------------------------------------------------------------------*/ ST_FN int dynarray_assoc(void **pp, int n, int key) { int i; for (i = 0; i < n; ++i, ++pp) if (key == **(int **) pp) return i; return -1; } #if 0 ST_FN DWORD umin(DWORD a, DWORD b) { return a < b ? a : b; } #endif ST_FN DWORD umax(DWORD a, DWORD b) { return a < b ? b : a; } ST_FN void pe_fpad(FILE *fp, DWORD new_pos) { DWORD pos = ftell(fp); while (++pos <= new_pos) fputc(0, fp); } ST_FN DWORD pe_file_align(DWORD n) { return (n + (0x200 - 1)) & ~(0x200 - 1); } ST_FN DWORD pe_virtual_align(DWORD n) { return (n + (0x1000 - 1)) & ~(0x1000 - 1); } ST_FN void pe_align_section(Section *s, int a) { int i = s->data_offset & (a-1); if (i) section_ptr_add(s, a - i); } ST_FN void pe_set_datadir(int dir, DWORD addr, DWORD size) { pe_header.opthdr.DataDirectory[dir].VirtualAddress = addr; pe_header.opthdr.DataDirectory[dir].Size = size; } /*----------------------------------------------------------------------------*/ ST_FN int pe_write(struct pe_info *pe) { int i; FILE *op; DWORD file_offset, r; op = fopen(pe->filename, "wb"); if (NULL == op) { error_noabort("could not write '%s': %s", pe->filename, strerror(errno)); return 1; } pe->sizeofheaders = pe_file_align( sizeof pe_header + pe->sec_count * sizeof (IMAGE_SECTION_HEADER) ); file_offset = pe->sizeofheaders; pe_fpad(op, file_offset); if (2 == pe->s1->verbose) printf("-------------------------------" "\n virt file size section" "\n"); for (i = 0; i < pe->sec_count; ++i) { struct section_info *si = pe->sec_info + i; const char *sh_name = si->name; unsigned long addr = si->sh_addr - pe->imagebase; unsigned long size = si->sh_size; IMAGE_SECTION_HEADER *psh = &si->ish; if (2 == pe->s1->verbose) printf("%6lx %6lx %6lx %s\n", addr, file_offset, size, sh_name); switch (si->cls) { case sec_text: pe_header.opthdr.BaseOfCode = addr; pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr; break; case sec_data: pe_header.opthdr.BaseOfData = addr; break; case sec_bss: break; case sec_reloc: pe_set_datadir(IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size); break; case sec_rsrc: pe_set_datadir(IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size); break; case sec_stab: break; } if (pe->thunk == pe->s1->sections[si->ord]) { if (pe->imp_size) { pe_set_datadir(IMAGE_DIRECTOR
/*
 * (C)opyright MMVI Anselm R. Garbe <garbeam at gmail dot com>
 * See LICENSE file for license details.
 */
#include "dwm.h"

#include <stdlib.h>
#include <string.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>

/* static functions */

static void
resizetitle(Client *c)
{
	int i;

	c->tw = 0;
	for(i = 0; i < TLast; i++)
		if(c->tags[i])
			c->tw += textw(c->tags[i]);
	c->tw += textw(c->name);
	if(c->tw > c->w)
		c->tw = c->w + 2;
	c->tx = c->x + c->w - c->tw + 2;
	c->ty = c->y;
	if(c->tags[tsel])
		XMoveResizeWindow(dpy, c->title, c->tx, c->ty, c->tw, c->th);
	else
		XMoveResizeWindow(dpy, c->title, c->tx + 2 * sw, c->ty, c->tw, c->th);

}

static int
xerrordummy(Display *dsply, XErrorEvent *ee)
{
	return 0;
}

/* extern functions */

void
ban(Client *c)
{
	XMoveWindow(dpy, c->win, c->x + 2 * sw, c->y);
	XMoveWindow(dpy, c->title, c->tx + 2 * sw, c->ty);
}

void
focus(Client *c)
{
	Client *old = sel;
	XEvent ev;

	sel = c;
	if(old && old != c)
		drawtitle(old);
	drawtitle(c);
	XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime);
	XSync(dpy, False);
	while(XCheckMaskEvent(dpy, EnterWindowMask, &ev));
}

void
focusnext(Arg *arg)
{
	Client *c;
   
	if(!sel)
		return;

	if(sel->ismax)
		togglemax(NULL);

	if(!(c = getnext(sel->next, tsel)))
		c = getnext(clients, tsel);
	if(c) {
		higher(c);
		c->revert = sel;
		focus(c);
	}
}

void
focusprev(Arg *arg)
{
	Client *c;

	if(!sel)
		return;

	if(sel->ismax)
		togglemax(NULL);

	if((c = sel->revert && sel->revert->tags[tsel] ? sel->revert : NULL)) {
		higher(c);
		focus(c);
	}
}

Client *
getclient(Window w)
{
	Client *c;

	for(c = clients; c; c = c->next)
		if(c->win == w)
			return c;
	return NULL;
}

Client *
getctitle(Window w)
{
	Client *c;

	for(c = clients; c; c = c->next)
		if(c->title == w)
			return c;
	return NULL;
}

void
gravitate(Client *c, Bool invert)
{
	int dx = 0, dy = 0;

	switch(c->grav) {
	case StaticGravity:
	case NorthWestGravity:
	case NorthGravity:
	case NorthEastGravity:
		dy = c->border;
		break;
	case EastGravity:
	case CenterGravity:
	case WestGravity:
		dy = -(c->h / 2) + c->border;
		break;
	case SouthEastGravity:
	case SouthGravity:
	case SouthWestGravity:
		dy = -(c->h);
		break;
	default:
		break;
	}

	switch (c->grav) {
	case StaticGravity:
	cas