summaryrefslogtreecommitdiffstats
path: root/toolkit/crashreporter/LoadLibraryRemote.cpp
blob: d0422edd08e912af352e3c8e7617eb051724df2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef __GNUC__
// disable warnings about pointer <-> DWORD conversions
#  pragma warning(disable : 4311 4312)
#endif

#ifdef _WIN64
#  define POINTER_TYPE ULONGLONG
#else
#  define POINTER_TYPE DWORD
#endif

#include <windows.h>
#include <winnt.h>
#include <stdlib.h>
#ifdef DEBUG_OUTPUT
#  include <stdio.h>
#endif

#include "nsWindowsHelpers.h"

typedef const unsigned char* FileView;

template <>
class nsAutoRefTraits<FileView> {
 public:
  typedef FileView RawRef;
  static FileView Void() { return nullptr; }

  static void Release(RawRef aView) {
    if (nullptr != aView) UnmapViewOfFile(aView);
  }
};

#ifndef IMAGE_SIZEOF_BASE_RELOCATION
// Vista SDKs no longer define IMAGE_SIZEOF_BASE_RELOCATION!?
#  define IMAGE_SIZEOF_BASE_RELOCATION (sizeof(IMAGE_BASE_RELOCATION))
#endif

#include "LoadLibraryRemote.h"

typedef struct {
  PIMAGE_NT_HEADERS headers;
  unsigned char* localCodeBase;
  unsigned char* remoteCodeBase;
  HMODULE* modules;
  int numModules;
} MEMORYMODULE, *PMEMORYMODULE;

typedef BOOL(WINAPI* DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason,
                                   LPVOID lpReserved);

#define GET_HEADER_DICTIONARY(module, idx) \
  &(module)->headers->OptionalHeader.DataDirectory[idx]

#ifdef DEBUG_OUTPUT
static void OutputLastError(const char* msg) {
  char* tmp;
  char* tmpmsg;
  FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
                     FORMAT_MESSAGE_IGNORE_INSERTS,
                 nullptr, GetLastError(),
                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&tmp, 0,
                 nullptr);
  tmpmsg = (char*)LocalAlloc(LPTR, strlen(msg) + strlen(tmp) + 3);
  sprintf(tmpmsg, "%s: %s", msg, tmp);
  OutputDebugStringA(tmpmsg);
  LocalFree(tmpmsg);
  LocalFree(tmp);
}
#endif

static void CopySections(const unsigned char* data,
                         PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module) {
  int i;
  unsigned char* codeBase = module->localCodeBase;
  unsigned char* dest;
  PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers);
  for (i = 0; i < module->headers->FileHeader.NumberOfSections;
       i++, section++) {
    dest = codeBase + section->VirtualAddress;
    memset(dest, 0, section->Misc.VirtualSize);
    if (section->SizeOfRawData) {
      memcpy(dest, data + section->PointerToRawData, section->SizeOfRawData);
    }
    // section->Misc.PhysicalAddress = (POINTER_TYPE) module->remoteCodeBase +
    //                                                section->VirtualAddress;
  }
}

static bool CopyRegion(HANDLE hRemoteProcess, void* remoteAddress,
                       void* localAddress, DWORD size, DWORD protect) {
  if (size > 0) {
    // Copy the data from local->remote and set the memory protection
    if (!VirtualAllocEx(hRemoteProcess, remoteAddress, size, MEM_COMMIT,
                        PAGE_READWRITE))
      return false;

    if (!WriteProcessMemory(hRemoteProcess, remoteAddress, localAddress, size,
                            nullptr)) {
#ifdef DEBUG_OUTPUT
      OutputLastError("Error writing remote memory.\n");
#endif
      return false;
    }

    DWORD oldProtect;
    if (VirtualProtectEx(hRemoteProcess, remoteAddress, size, protect,
                         &oldProtect) == 0) {
#ifdef DEBUG_OUTPUT
      OutputLastError("Error protecting memory page");
#endif
      return false;
    }
  }
  return true;
}
// Protection flags for memory pages (Executable, Readable, Writeable)
static int ProtectionFlags[2][2][2] = {
    {
        // not executable
        {PAGE_NOACCESS, PAGE_WRITECOPY},
        {PAGE_READONLY, PAGE_READWRITE},
    },
    {
        // executable
        {PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY},
        {PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE},
    },
};

static bool FinalizeSections(PMEMORYMODULE module, HANDLE hRemoteProcess) {
#ifdef DEBUG_OUTPUT
  fprintf(stderr, "Finalizing sections: local base %p, remote base %p\n",
          module->localCodeBase, module->remoteCodeBase);
#endif

  int i;
  int numSections = module->headers->FileHeader.NumberOfSections;

  if (numSections < 1) return false;

  PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(module->headers);

  // Copy any data before the first section (i.e. the image header)
  if (!CopyRegion(hRemoteProcess, module->remoteCodeBase, module->localCodeBase,
                  section->VirtualAddress, PAGE_READONLY))
    return false;

  // loop through all sections and change access flags
  for (i = 0; i < numSections; i++, section++) {
    DWORD protect, size;
    int executable = (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0;
    int readable = (section->Characteristics & IMAGE_SCN_MEM_READ) != 0;
    int writeable = (section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0;

    // determine protection flags based on characteristics
    protect = ProtectionFlags[executable][readable][writeable];
    if (section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED) {
      protect |= PAGE_NOCACHE;
    }

    void* remoteAddress = module->remoteCodeBase + section->VirtualAddress;
    void* localAddress = module->localCodeBase + section->VirtualAddress;

    // determine size of region
    size = section->Misc.VirtualSize;
#ifdef DEBUG_OUTPUT
    fprintf(stderr,
            "Copying section %s to %p, size %x, executable %i readable %i "
            "writeable %i\n",
            section->Name, remoteAddress, size, executable, readable,
            writeable);
#endif
    if (!CopyRegion(hRemoteProcess, remoteAddress, localAddress, size, protect))
      return false;
  }
  return true;
}

static void PerformBaseRelocation(PMEMORYMODULE module, SIZE_T delta) {
  DWORD i;
  unsigned char* codeBase = module->localCodeBase;

  PIMAGE_DATA_DIRECTORY directory =
      GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_BASERELOC);
  if (directory->Size > 0) {
    PIMAGE_BASE_RELOCATION relocation =
        (PIMAGE_BASE_RELOCATION)(codeBase + directory->VirtualAddress);
    for (; relocation->VirtualAddress > 0;) {
      unsigned char* dest = codeBase + relocation->VirtualAddress;
      unsigned short* relInfo = (unsigned short*)((unsigned char*)relocation +
                                                  IMAGE_SIZEOF_BASE_RELOCATION);
      for (i = 0;
           i < ((relocation->SizeOfBlock - IMAGE_SIZEOF_BASE_RELOCATION) / 2);
           i++, relInfo++) {
        DWORD* patchAddrHL;
#ifdef _WIN64
        ULONGLONG* patchAddr64;
#endif
        int type, offset;

        // the upper 4 bits define the type of relocation
        type = *relInfo >> 12;
        // the lower 12 bits define the offset
        offset = *relInfo & 0xfff;

        switch (type) {
          case IMAGE_REL_BASED_ABSOLUTE:
            // skip relocation
            break;

          case IMAGE_REL_BASED_HIGHLOW:
            // change complete 32 bit address
            patchAddrHL = (DWORD*)(dest + offset);
            *patchAddrHL += delta;
            break;

#ifdef _WIN64
          case IMAGE_REL_BASED_DIR64:
            patchAddr64 = (ULONGLONG*)(dest + offset);
            *patchAddr64 += delta;
            break;
#endif

          default:
            // printf("Unknown relocation: %d\n", type);
            break;
        }
      }

      // advance to next relocation block
      relocation = (PIMAGE_BASE_RELOCATION)(((char*)relocation) +
                                            relocation->SizeOfBlock);
    }
  }
}

static int BuildImportTable(PMEMORYMODULE module) {
  int result = 1;
  unsigned char* codeBase = module->localCodeBase;

  PIMAGE_DATA_DIRECTORY directory =
      GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT);
  if (directory->Size > 0) {
    PIMAGE_IMPORT_DESCRIPTOR importDesc =
        (PIMAGE_IMPORT_DESCRIPTOR)(codeBase + directory->VirtualAddress);
    PIMAGE_IMPORT_DESCRIPTOR importEnd =
        (PIMAGE_IMPORT_DESCRIPTOR)(codeBase + directory->VirtualAddress +
                                   directory->Size);

    for (; importDesc < importEnd && importDesc->Name; importDesc++) {
      POINTER_TYPE* thunkRef;
      FARPROC* funcRef;
      HMODULE handle = GetModuleHandleA((LPCSTR)(codeBase + importDesc->Name));
      if (handle == nullptr) {
#if DEBUG_OUTPUT
        OutputLastError("Can't load library");
#endif
        result = 0;
        break;
      }

      module->modules = (HMODULE*)realloc(
          module->modules, (module->numModules + 1) * (sizeof(HMODULE)));
      if (module->modules == nullptr) {
        result = 0;
        break;
      }

      module->modules[module->numModules++] = handle;
      if (importDesc->OriginalFirstThunk) {
        thunkRef = (POINTER_TYPE*)(codeBase + importDesc->OriginalFirstThunk);
        funcRef = (FARPROC*)(codeBase + importDesc->FirstThunk);
      } else {
        // no hint table
        thunkRef = (POINTER_TYPE*)(codeBase + importDesc->FirstThunk);
        funcRef = (FARPROC*)(codeBase + importDesc->FirstThunk);
      }
      for (; *thunkRef; thunkRef++, funcRef++) {
        if (IMAGE_SNAP_BY_ORDINAL(*thunkRef)) {
          *funcRef =
              (FARPROC)GetProcAddress(handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef));
        } else {
          PIMAGE_IMPORT_BY_NAME thunkData =
              (PIMAGE_IMPORT_BY_NAME)(codeBase + (*thunkRef));
          *funcRef = (FARPROC)GetProcAddress(handle, (LPCSTR)&thunkData->Name);
        }
        if (*funcRef == 0) {
          result = 0;
          break;
        }
      }

      if (!result) {
        break;
      }
    }
  }

  return result;
}

static void* MemoryGetProcAddress(PMEMORYMODULE module, const char* name);

void* LoadRemoteLibraryAndGetAddress(HANDLE hRemoteProcess,
                                     const WCHAR* library, const char* symbol) {
  // Map the DLL into memory
  nsAutoHandle hLibrary(CreateFile(library, GENERIC_READ, FILE_SHARE_READ,
                                   nullptr, OPEN_EXISTING,
                                   FILE_ATTRIBUTE_NORMAL, nullptr));
  if (INVALID_HANDLE_VALUE == hLibrary) {
#if DEBUG_OUTPUT
    OutputLastError("Couldn't CreateFile the library.\n");
#endif
    return nullptr;
  }

  nsAutoHandle hMapping(
      CreateFileMapping(hLibrary, nullptr, PAGE_READONLY, 0, 0, nullptr));
  if (!hMapping) {
#if DEBUG_OUTPUT
    OutputLastError("Couldn't CreateFileMapping.\n");
#endif
    return nullptr;
  }

  nsAutoRef<FileView> data(
      (const unsigned char*)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0));
  if (!data) {
#if DEBUG_OUTPUT
    OutputLastError("Couldn't MapViewOfFile.\n");
#endif
    return nullptr;
  }

  SIZE_T locationDelta;

  PIMAGE_DOS_HEADER dos_header = (PIMAGE_DOS_HEADER)data.get();
  if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
#if DEBUG_OUTPUT
    OutputDebugStringA("Not a valid executable file.\n");
#endif
    return nullptr;
  }

  PIMAGE_NT_HEADERS old_header =
      (PIMAGE_NT_HEADERS)(data + dos_header->e_lfanew);
  if (old_header->Signature != IMAGE_NT_SIGNATURE) {
#if DEBUG_OUTPUT
    OutputDebugStringA("No PE header found.\n");
#endif
    return nullptr;
  }

  // reserve memory for image of library in this process and the target process
  unsigned char* localCode = (unsigned char*)VirtualAlloc(
      nullptr, old_header->OptionalHeader.SizeOfImage, MEM_RESERVE | MEM_COMMIT,
      PAGE_READWRITE);
  if (!localCode) {
#if DEBUG_OUTPUT
    OutputLastError("Can't reserve local memory.");
#endif
  }

  unsigned char* remoteCode = (unsigned char*)VirtualAllocEx(
      hRemoteProcess, nullptr, old_header->OptionalHeader.SizeOfImage,
      MEM_RESERVE, PAGE_EXECUTE_READ);
  if (!remoteCode) {
#if DEBUG_OUTPUT
    OutputLastError("Can't reserve remote memory.");
#endif
  }

  MEMORYMODULE result;
  result.localCodeBase = localCode;
  result.remoteCodeBase = remoteCode;
  result.numModules = 0;
  result.modules = nullptr;

  // copy PE header to code
  memcpy(localCode, dos_header,
         dos_header->e_lfanew + old_header->OptionalHeader.SizeOfHeaders);
  result.headers =
      reinterpret_cast<PIMAGE_NT_HEADERS>(localCode + dos_header->e_lfanew);

  // update position
  result.headers->OptionalHeader.ImageBase = (POINTER_TYPE)remoteCode;

  // copy sections from DLL file block to new memory location
  CopySections(data, old_header, &result);

  // adjust base address of imported data
  locationDelta = (SIZE_T)(remoteCode - old_header->OptionalHeader.ImageBase);
  if (locationDelta != 0) {
    PerformBaseRelocation(&result, locationDelta);
  }

  // load required dlls and adjust function table of imports
  if (!BuildImportTable(&result)) {
    return nullptr;
  }

  // mark memory pages depending on section headers and release
  // sections that are marked as "discardable"
  if (!FinalizeSections(&result, hRemoteProcess)) {
    return nullptr;
  }

  return MemoryGetProcAddress(&result, symbol);
}

static void* MemoryGetProcAddress(PMEMORYMODULE module, const char* name) {
  unsigned char* localCodeBase = module->localCodeBase;
  int idx = -1;
  DWORD i, *nameRef;
  WORD* ordinal;
  PIMAGE_EXPORT_DIRECTORY exports;
  PIMAGE_DATA_DIRECTORY directory =
      GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_EXPORT);
  if (directory->Size == 0) {
    // no export table found
    return nullptr;
  }

  exports =
      (PIMAGE_EXPORT_DIRECTORY)(localCodeBase + directory->VirtualAddress);
  if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) {
    // DLL doesn't export anything
    return nullptr;
  }

  // search function name in list of exported names
  nameRef = (DWORD*)(localCodeBase + exports->AddressOfNames);
  ordinal = (WORD*)(localCodeBase + exports->AddressOfNameOrdinals);
  for (i = 0; i < exports->NumberOfNames; i++, nameRef++, ordinal++) {
    if (stricmp(name, (const char*)(localCodeBase + (*nameRef))) == 0) {
      idx = *ordinal;
      break;
    }
  }

  if (idx == -1) {
    // exported symbol not found
    return nullptr;
  }

  if ((DWORD)idx > exports->NumberOfFunctions) {
    // name <-> ordinal number don't match
    return nullptr;
  }

  // AddressOfFunctions contains the RVAs to the "real" functions
  return module->remoteCodeBase +
         (*(DWORD*)(localCodeBase + exports->AddressOfFunctions + (idx * 4)));
}