summaryrefslogtreecommitdiffstats
path: root/mozglue/tests/TestPEExportSection.cpp
blob: cf160368d39454234916e77610daf514e4b6e479 (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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 https://mozilla.org/MPL/2.0/. */

// This test makes sure mozilla::nt::PEExportSection can parse the export
// section of a local process, and a remote process even though it's
// modified by an external code.

#include "mozilla/CmdLineAndEnvUtils.h"
#include "mozilla/NativeNt.h"
#include "nsWindowsDllInterceptor.h"

#include <stdio.h>
#include <windows.h>

#define EXPORT_FUNCTION_EQ(name, func) \
  (GetProcAddress(imageBase, name) == reinterpret_cast<void*>(func))

#define VERIFY_EXPORT_FUNCTION(tables, name, expected, errorMessage)        \
  do {                                                                      \
    if (tables.GetProcAddress(name) != reinterpret_cast<void*>(expected)) { \
      printf("TEST-FAILED | TestPEExportSection | %s", errorMessage);       \
      return kTestFail;                                                     \
    }                                                                       \
  } while (0)

using namespace mozilla::nt;
using mozilla::interceptor::MMPolicyInProcess;
using mozilla::interceptor::MMPolicyOutOfProcess;
using LocalPEExportSection = PEExportSection<MMPolicyInProcess>;
using RemotePEExportSection = PEExportSection<MMPolicyOutOfProcess>;

constexpr DWORD kEventTimeoutinMs = 5000;
const wchar_t kProcessControlEventName[] =
    L"TestPEExportSection.Process.Control.Event";

enum TestResult : int {
  kTestSuccess = 0,
  kTestFail,
  kTestSkip,
};

// These strings start with the same keyword to make sure we don't do substring
// match.  Moreover, kSecretFunctionInvalid is purposely longer than the
// combination of the other two strings and located in between the other two
// strings to effectively test binary search.
const char kSecretFunction[] = "Secret";
const char kSecretFunctionInvalid[] = "Secret invalid long name";
const char kSecretFunctionWithSuffix[] = "Secret2";

const wchar_t* kNoModification = L"--NoModification";
const wchar_t* kNoExport = L"--NoExport";
const wchar_t* kModifyTableEntry = L"--ModifyTableEntry";
const wchar_t* kModifyTable = L"--ModifyTable";
const wchar_t* kModifyDirectoryEntry = L"--ModifyDirectoryEntry";
const wchar_t* kExportByOrdinal = L"--ExportByOrdinal";

// Use the global variable to pass the child process's error status to the
// parent process.  We don't use a process's exit code to keep the test simple.
int gChildProcessStatus = 0;

// These functions are exported by linker or export section tampering at
// runtime.  Each of function bodies needs to be different to avoid ICF.
extern "C" __declspec(dllexport) int Export1() { return 0; }
extern "C" __declspec(dllexport) int Export2() { return 1; }
int SecretFunction1() { return 100; }
int SecretFunction2() { return 101; }

// This class allocates a writable region downstream of the mapped image
// and prepares it as a valid export section.
class ExportDirectoryPatcher final {
  static constexpr int kRegionAllocationTryLimit = 100;
  static constexpr int kNumOfTableEntries = 2;
  // VirtualAlloc sometimes fails if a desired base address is too small.
  // Define a minimum desired base to reduce the number of allocation tries.
  static constexpr uintptr_t kMinimumAllocationPoint = 0x8000000;

  struct ExportDirectory {
    IMAGE_EXPORT_DIRECTORY mDirectoryHeader;
    DWORD mExportAddressTable[kNumOfTableEntries];
    DWORD mExportNameTable[kNumOfTableEntries];
    WORD mExportOrdinalTable[kNumOfTableEntries];
    char mNameBuffer1[sizeof(kSecretFunction)];
    char mNameBuffer2[sizeof(kSecretFunctionWithSuffix)];

    template <typename T>
    static DWORD PtrToRVA(T aPtr, uintptr_t aBase) {
      return reinterpret_cast<uintptr_t>(aPtr) - aBase;
    }

    explicit ExportDirectory(uintptr_t aImageBase) : mDirectoryHeader{} {
      mDirectoryHeader.Base = 1;
      mExportAddressTable[0] = PtrToRVA(SecretFunction1, aImageBase);
      mExportAddressTable[1] = PtrToRVA(SecretFunction2, aImageBase);
      mExportNameTable[0] = PtrToRVA(mNameBuffer1, aImageBase);
      mExportNameTable[1] = PtrToRVA(mNameBuffer2, aImageBase);
      mExportOrdinalTable[0] = 0;
      mExportOrdinalTable[1] = 1;
      strcpy(mNameBuffer1, kSecretFunction);
      strcpy(mNameBuffer2, kSecretFunctionWithSuffix);
    }
  };

  uintptr_t mImageBase;
  ExportDirectory* mNewExportDirectory;

  DWORD PtrToRVA(const void* aPtr) const {
    return reinterpret_cast<uintptr_t>(aPtr) - mImageBase;
  }

 public:
  explicit ExportDirectoryPatcher(HMODULE aModule)
      : mImageBase(PEHeaders::HModuleToBaseAddr<uintptr_t>(aModule)),
        mNewExportDirectory(nullptr) {
    SYSTEM_INFO si = {};
    ::GetSystemInfo(&si);

    int numPagesRequired = ((sizeof(ExportDirectory) - 1) / si.dwPageSize) + 1;

    uintptr_t desiredBase = mImageBase + si.dwAllocationGranularity;
    desiredBase = std::max(desiredBase, kMinimumAllocationPoint);

    for (int i = 0; i < kRegionAllocationTryLimit; ++i) {
      void* allocated =
          ::VirtualAlloc(reinterpret_cast<void*>(desiredBase),
                         numPagesRequired * si.dwPageSize,
                         MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
      if (allocated) {
        // Use the end of a allocated page as ExportDirectory in order to test
        // the boundary between a commit page and a non-commited page.
        allocated = reinterpret_cast<uint8_t*>(allocated) +
                    (numPagesRequired * si.dwPageSize) -
                    sizeof(ExportDirectory);
        mNewExportDirectory = new (allocated) ExportDirectory(mImageBase);
        return;
      }

      desiredBase += si.dwAllocationGranularity;
    }

    gChildProcessStatus = kTestSkip;
    printf(
        "TEST-SKIP | TestPEExportSection | "
        "Giving up finding an allocatable space following the mapped image.\n");
  }

  ~ExportDirectoryPatcher() {
    // Intentionally leave mNewExportDirectory leaked to keep a patched data
    // available until the process is terminated.
  }

  explicit operator bool() const { return !!mNewExportDirectory; }

  void PopulateDirectory(IMAGE_EXPORT_DIRECTORY& aOutput) const {
    aOutput.NumberOfFunctions = aOutput.NumberOfNames = kNumOfTableEntries;
    aOutput.AddressOfFunctions =
        PtrToRVA(mNewExportDirectory->mExportAddressTable);
    aOutput.AddressOfNames = PtrToRVA(mNewExportDirectory->mExportNameTable);
    aOutput.AddressOfNameOrdinals =
        PtrToRVA(mNewExportDirectory->mExportOrdinalTable);
  }

  void PopulateDirectoryEntry(IMAGE_DATA_DIRECTORY& aOutput) const {
    PopulateDirectory(mNewExportDirectory->mDirectoryHeader);
    aOutput.VirtualAddress = PtrToRVA(&mNewExportDirectory->mDirectoryHeader);
    aOutput.Size = sizeof(ExportDirectory);
  }
};

// This exports SecretFunction1 as "Export1" by replacing an entry of the
// export address table.
void ModifyExportAddressTableEntry() {
  MMPolicyInProcess policy;
  HMODULE imageBase = ::GetModuleHandleW(nullptr);
  auto ourExe = LocalPEExportSection::Get(imageBase, policy);

  auto addressTableEntry =
      const_cast<DWORD*>(ourExe.FindExportAddressTableEntry("Export1"));
  if (!addressTableEntry) {
    gChildProcessStatus = kTestFail;
    return;
  }

  mozilla::AutoVirtualProtect protection(
      addressTableEntry, sizeof(*addressTableEntry), PAGE_READWRITE);
  if (!protection) {
    gChildProcessStatus = kTestFail;
    return;
  }

  *addressTableEntry = reinterpret_cast<uintptr_t>(SecretFunction1) -
                       PEHeaders::HModuleToBaseAddr<uintptr_t>(imageBase);

  if (!EXPORT_FUNCTION_EQ("Export1", SecretFunction1) ||
      !EXPORT_FUNCTION_EQ("Export2", Export2)) {
    gChildProcessStatus = kTestFail;
  }
}

// This switches the entire address table into one exporting SecretFunction1
// and SecretFunction2.
void ModifyExportAddressTable() {
  MMPolicyInProcess policy;
  HMODULE imageBase = ::GetModuleHandleW(nullptr);
  auto ourExe = LocalPEExportSection::Get(imageBase, policy);

  auto exportDirectory = ourExe.GetExportDirectory();
  if (!exportDirectory) {
    gChildProcessStatus = kTestFail;
    return;
  }

  mozilla::AutoVirtualProtect protection(
      exportDirectory, sizeof(*exportDirectory), PAGE_READWRITE);
  if (!protection) {
    gChildProcessStatus = kTestFail;
    return;
  }

  ExportDirectoryPatcher patcher(imageBase);
  if (!patcher) {
    return;
  }

  patcher.PopulateDirectory(*exportDirectory);

  if (GetProcAddress(imageBase, "Export1") ||
      GetProcAddress(imageBase, "Export2") ||
      !EXPORT_FUNCTION_EQ(kSecretFunction, SecretFunction1) ||
      !EXPORT_FUNCTION_EQ(kSecretFunctionWithSuffix, SecretFunction2)) {
    gChildProcessStatus = kTestFail;
  }
}

// This hides all export functions by setting the table size to 0.
void HideExportSection() {
  HMODULE imageBase = ::GetModuleHandleW(nullptr);
  PEHeaders ourExe(imageBase);

  auto sectionTable =
      ourExe.GetImageDirectoryEntryPtr(IMAGE_DIRECTORY_ENTRY_EXPORT);

  mozilla::AutoVirtualProtect protection(sectionTable, sizeof(*sectionTable),
                                         PAGE_READWRITE);
  if (!protection) {
    gChildProcessStatus = kTestFail;
    return;
  }

  sectionTable->VirtualAddress = sectionTable->Size = 0;

  if (GetProcAddress(imageBase, "Export1") ||
      GetProcAddress(imageBase, "Export2")) {
    gChildProcessStatus = kTestFail;
  }
}

// This makes the export directory entry point to a new export section
// which exports SecretFunction1 and SecretFunction2.
void ModifyExportDirectoryEntry() {
  HMODULE imageBase = ::GetModuleHandleW(nullptr);
  PEHeaders ourExe(imageBase);

  auto sectionTable =
      ourExe.GetImageDirectoryEntryPtr(IMAGE_DIRECTORY_ENTRY_EXPORT);

  mozilla::AutoVirtualProtect protection(sectionTable, sizeof(*sectionTable),
                                         PAGE_READWRITE);
  if (!protection) {
    gChildProcessStatus = kTestFail;
    return;
  }

  ExportDirectoryPatcher patcher(imageBase);
  if (!patcher) {
    return;
  }

  patcher.PopulateDirectoryEntry(*sectionTable);

  if (GetProcAddress(imageBase, "Export1") ||
      GetProcAddress(imageBase, "Export2") ||
      !EXPORT_FUNCTION_EQ(kSecretFunction, SecretFunction1) ||
      !EXPORT_FUNCTION_EQ(kSecretFunctionWithSuffix, SecretFunction2)) {
    gChildProcessStatus = kTestFail;
  }
}

// This exports functions only by Ordinal by hiding the export name table.
void ExportByOrdinal() {
  ModifyExportDirectoryEntry();
  if (gChildProcessStatus != kTestSuccess) {
    return;
  }

  MMPolicyInProcess policy;
  HMODULE imageBase = ::GetModuleHandleW(nullptr);
  auto ourExe = LocalPEExportSection::Get(imageBase, policy);

  auto exportDirectory = ourExe.GetExportDirectory();
  if (!exportDirectory) {
    gChildProcessStatus = kTestFail;
    return;
  }

  exportDirectory->NumberOfNames = 0;

  if (GetProcAddress(imageBase, "Export1") ||
      GetProcAddress(imageBase, "Export2") ||
      GetProcAddress(imageBase, kSecretFunction) ||
      GetProcAddress(imageBase, kSecretFunctionWithSuffix) ||
      !EXPORT_FUNCTION_EQ(MAKEINTRESOURCE(1), SecretFunction1) ||
      !EXPORT_FUNCTION_EQ(MAKEINTRESOURCE(2), SecretFunction2)) {
    gChildProcessStatus = kTestFail;
  }
}

class ChildProcess final {
  nsAutoHandle mChildProcess;
  nsAutoHandle mChildMainThread;

 public:
  static int Main(const nsAutoHandle& aEvent, const wchar_t* aOption) {
    if (wcscmp(aOption, kNoModification) == 0) {
      ;
    } else if (wcscmp(aOption, kNoExport) == 0) {
      HideExportSection();
    } else if (wcscmp(aOption, kModifyTableEntry) == 0) {
      ModifyExportAddressTableEntry();
    } else if (wcscmp(aOption, kModifyTable) == 0) {
      ModifyExportAddressTable();
    } else if (wcscmp(aOption, kModifyDirectoryEntry) == 0) {
      ModifyExportDirectoryEntry();
    } else if (wcscmp(aOption, kExportByOrdinal) == 0) {
      ExportByOrdinal();
    }

    // Letting the parent process know the child process is ready.
    ::SetEvent(aEvent);

    // The child process does not exit itself.  It's force terminated by
    // the parent process when all tests are done.
    for (;;) {
      ::Sleep(100);
    }
  }

  ChildProcess(const wchar_t* aExecutable, const wchar_t* aOption,
               const nsAutoHandle& aEvent, const nsAutoHandle& aJob) {
    const wchar_t* childArgv[] = {aExecutable, aOption};
    auto cmdLine(
        mozilla::MakeCommandLine(mozilla::ArrayLength(childArgv), childArgv));

    STARTUPINFOW si = {sizeof(si)};
    PROCESS_INFORMATION pi;
    BOOL ok = ::CreateProcessW(aExecutable, cmdLine.get(), nullptr, nullptr,
                               FALSE, 0, nullptr, nullptr, &si, &pi);
    if (!ok) {
      printf(
          "TEST-FAILED | TestPEExportSection | "
          "CreateProcessW falied - %08lx.\n",
          GetLastError());
      return;
    }

    if (aJob && !::AssignProcessToJobObject(aJob, pi.hProcess)) {
      printf(
          "TEST-FAILED | TestPEExportSection | "
          "AssignProcessToJobObject falied - %08lx.\n",
          GetLastError());
      ::TerminateProcess(pi.hProcess, 1);
      return;
    }

    // Wait until requested modification is done in the child process.
    if (::WaitForSingleObject(aEvent, kEventTimeoutinMs) != WAIT_OBJECT_0) {
      printf(
          "TEST-FAILED | TestPEExportSection | "
          "Child process was not ready in time.\n");
      return;
    }

    mChildProcess.own(pi.hProcess);
    mChildMainThread.own(pi.hThread);
  }

  ~ChildProcess() { ::TerminateProcess(mChildProcess, 0); }

  operator HANDLE() const { return mChildProcess; }

  TestResult GetStatus() const {
    TestResult status = kTestSuccess;
    if (!::ReadProcessMemory(mChildProcess, &gChildProcessStatus, &status,
                             sizeof(status), nullptr)) {
      status = kTestFail;
      printf(
          "TEST-FAILED | TestPEExportSection | "
          "ReadProcessMemory failed - %08lx\n",
          GetLastError());
    }
    return status;
  }
};

template <typename MMPolicy>
TestResult BasicTest(const MMPolicy& aMMPolicy) {
  const bool isAppHelpLoaded = ::GetModuleHandleW(L"apphelp.dll");

  // Use ntdll.dll because it does not have any forwarder RVA.
  HMODULE ntdllImageBase = ::GetModuleHandleW(L"ntdll.dll");
  auto ntdllExports = PEExportSection<MMPolicy>::Get(ntdllImageBase, aMMPolicy);

  auto exportDir = ntdllExports.GetExportDirectory();
  auto tableOfNames =
      ntdllExports.template RVAToPtr<const PDWORD>(exportDir->AddressOfNames);
  for (DWORD i = 0; i < exportDir->NumberOfNames; ++i) {
    const auto name =
        ntdllExports.template RVAToPtr<const char*>(tableOfNames[i]);

    if (isAppHelpLoaded && strcmp(name, "NtdllDefWindowProc_W") == 0) {
      // In this case, GetProcAddress will return
      // apphelp!DWM8AND16BitHook_DefWindowProcW.
      continue;
    }

    auto funcEntry = ntdllExports.FindExportAddressTableEntry(name);
    if (ntdllExports.template RVAToPtr<const void*>(*funcEntry) !=
        ::GetProcAddress(ntdllImageBase, name)) {
      printf(
          "TEST-FAILED | TestPEExportSection | "
          "FindExportAddressTableEntry did not resolve ntdll!%s.\n",
          name);
      return kTestFail;
    }
  }

  for (DWORD i = 0; i < 0x10000; i += 0x10) {
    if (ntdllExports.GetProcAddress(MAKEINTRESOURCE(i)) !=
        ::GetProcAddress(ntdllImageBase, MAKEINTRESOURCE(i))) {
      printf(
          "TEST-FAILED | TestPEExportSection | "
          "GetProcAddress did not resolve ntdll!Ordinal#%lu.\n",
          i);
      return kTestFail;
    }
  }

  // Test a known forwarder RVA.
  auto k32Exports = PEExportSection<MMPolicy>::Get(
      ::GetModuleHandleW(L"kernel32.dll"), aMMPolicy);
  if (k32Exports.FindExportAddressTableEntry("HeapAlloc")) {
    printf(
        "TEST-FAILED | TestPEExportSection | "
        "kernel32!HeapAlloc should be forwarded to ntdll!RtlAllocateHeap.\n");
    return kTestFail;
  }

  // Test invalid names.
  if (k32Exports.FindExportAddressTableEntry("Invalid name") ||
      k32Exports.FindExportAddressTableEntry("")) {
    printf(
        "TEST-FAILED | TestPEExportSection | "
        "FindExportAddressTableEntry should return "
        "nullptr for a non-existent name.\n");
    return kTestFail;
  }

  return kTestSuccess;
}

TestResult RunChildProcessTest(
    const wchar_t* aExecutable, const wchar_t* aOption,
    const nsAutoHandle& aEvent, const nsAutoHandle& aJob,
    TestResult (*aTestCallback)(const RemotePEExportSection&)) {
  ChildProcess childProcess(aExecutable, aOption, aEvent, aJob);
  if (!childProcess) {
    return kTestFail;
  }

  auto result = childProcess.GetStatus();
  if (result != kTestSuccess) {
    return result;
  }

  MMPolicyOutOfProcess policy(childProcess);

  // One time is enough to run BasicTest in the child process.
  static TestResult oneTimeResult = BasicTest<MMPolicyOutOfProcess>(policy);
  if (oneTimeResult != kTestSuccess) {
    return oneTimeResult;
  }

  auto exportTableChild =
      RemotePEExportSection::Get(::GetModuleHandleW(nullptr), policy);
  return aTestCallback(exportTableChild);
}

mozilla::LauncherResult<nsReturnRef<HANDLE>> CreateJobToLimitProcessLifetime() {
  uint64_t version;
  PEHeaders ntdllHeaders(::GetModuleHandleW(L"ntdll.dll"));
  if (!ntdllHeaders.GetVersionInfo(version)) {
    printf(
        "TEST-FAILED | TestPEExportSection | "
        "Unable to obtain version information from ntdll.dll\n");
    return LAUNCHER_ERROR_FROM_LAST();
  }

  constexpr uint64_t kWin8 = 0x60002ull << 32;
  nsAutoHandle job;

  if (version < kWin8) {
    // Since a process can be associated only with a single job in Win7 or
    // older and this test program is already assigned with a job by
    // infrastructure, we cannot use a job.
    return job.out();
  }

  job.own(::CreateJobObject(nullptr, nullptr));
  if (!job) {
    printf(
        "TEST-FAILED | TestPEExportSection | "
        "CreateJobObject falied - %08lx.\n",
        GetLastError());
    return LAUNCHER_ERROR_FROM_LAST();
  }

  JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobInfo = {};
  jobInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;

  if (!::SetInformationJobObject(job, JobObjectExtendedLimitInformation,
                                 &jobInfo, sizeof(jobInfo))) {
    printf(
        "TEST-FAILED | TestPEExportSection | "
        "SetInformationJobObject falied - %08lx.\n",
        GetLastError());
    return LAUNCHER_ERROR_FROM_LAST();
  }

  return job.out();
}

extern "C" int wmain(int argc, wchar_t* argv[]) {
  nsAutoHandle controlEvent(
      ::CreateEventW(nullptr, FALSE, FALSE, kProcessControlEventName));

  if (argc == 2) {
    return ChildProcess::Main(controlEvent, argv[1]);
  }

  if (argc != 1) {
    printf(
        "TEST-FAILED | TestPEExportSection | "
        "Invalid arguments.\n");
    return kTestFail;
  }

  MMPolicyInProcess policy;
  if (BasicTest<MMPolicyInProcess>(policy)) {
    return kTestFail;
  }

  auto exportTableSelf =
      LocalPEExportSection::Get(::GetModuleHandleW(nullptr), policy);
  if (!exportTableSelf) {
    printf(
        "TEST-FAILED | TestPEExportSection | "
        "LocalPEExportSection::Get failed.\n");
    return kTestFail;
  }

  VERIFY_EXPORT_FUNCTION(exportTableSelf, "Export1", Export1,
                         "Local | Export1 was not exported.\n");
  VERIFY_EXPORT_FUNCTION(exportTableSelf, "Export2", Export2,
                         "Local | Export2 was not exported.\n");
  VERIFY_EXPORT_FUNCTION(
      exportTableSelf, "Invalid name", 0,
      "Local | GetProcAddress should return nullptr for an invalid name.\n");

  // We'll add the child process to a job so that, in the event of a failure in
  // this parent process, the child process will be automatically terminated.
  auto probablyJob = CreateJobToLimitProcessLifetime();
  if (probablyJob.isErr()) {
    return kTestFail;
  }

  nsAutoHandle job(probablyJob.unwrap());

  auto result = RunChildProcessTest(
      argv[0], kNoModification, controlEvent, job,
      [](const RemotePEExportSection& aTables) {
        VERIFY_EXPORT_FUNCTION(aTables, "Export1", Export1,
                               "NoModification | Export1 was not exported.\n");
        VERIFY_EXPORT_FUNCTION(aTables, "Export2", Export2,
                               "NoModification | Export2 was not exported.\n");
        return kTestSuccess;
      });
  if (result == kTestFail) {
    return result;
  }

  result = RunChildProcessTest(
      argv[0], kNoExport, controlEvent, job,
      [](const RemotePEExportSection& aTables) {
        VERIFY_EXPORT_FUNCTION(aTables, "Export1", 0,
                               "NoExport | Export1 was exported.\n");
        VERIFY_EXPORT_FUNCTION(aTables, "Export2", 0,
                               "NoExport | Export2 was exported.\n");
        return kTestSuccess;
      });
  if (result == kTestFail) {
    return result;
  }

  result = RunChildProcessTest(
      argv[0], kModifyTableEntry, controlEvent, job,
      [](const RemotePEExportSection& aTables) {
        VERIFY_EXPORT_FUNCTION(
            aTables, "Export1", SecretFunction1,
            "ModifyTableEntry | SecretFunction1 was not exported.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, "Export2", Export2,
            "ModifyTableEntry | Export2 was not exported.\n");
        return kTestSuccess;
      });
  if (result == kTestFail) {
    return result;
  }

  result = RunChildProcessTest(
      argv[0], kModifyTable, controlEvent, job,
      [](const RemotePEExportSection& aTables) {
        VERIFY_EXPORT_FUNCTION(aTables, "Export1", 0,
                               "ModifyTable | Export1 was exported.\n");
        VERIFY_EXPORT_FUNCTION(aTables, "Export2", 0,
                               "ModifyTable | Export2 was exported.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, kSecretFunction, SecretFunction1,
            "ModifyTable | SecretFunction1 was not exported.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, kSecretFunctionWithSuffix, SecretFunction2,
            "ModifyTable | SecretFunction2 was not exported.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, kSecretFunctionInvalid, 0,
            "ModifyTable | kSecretFunctionInvalid was exported.\n");
        return kTestSuccess;
      });
  if (result == kTestFail) {
    return result;
  }

  result = RunChildProcessTest(
      argv[0], kModifyDirectoryEntry, controlEvent, job,
      [](const RemotePEExportSection& aTables) {
        VERIFY_EXPORT_FUNCTION(
            aTables, "Export1", 0,
            "ModifyDirectoryEntry | Export1 was exported.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, "Export2", 0,
            "ModifyDirectoryEntry | Export2 was exported.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, kSecretFunction, SecretFunction1,
            "ModifyDirectoryEntry | SecretFunction1 was not exported.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, kSecretFunctionWithSuffix, SecretFunction2,
            "ModifyDirectoryEntry | SecretFunction2 was not exported.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, kSecretFunctionInvalid, 0,
            "ModifyDirectoryEntry | kSecretFunctionInvalid was exported.\n");
        return kTestSuccess;
      });
  if (result == kTestFail) {
    return result;
  }

  result = RunChildProcessTest(
      argv[0], kExportByOrdinal, controlEvent, job,
      [](const RemotePEExportSection& aTables) {
        VERIFY_EXPORT_FUNCTION(aTables, "Export1", 0,
                               "ExportByOrdinal | Export1 was exported.\n");
        VERIFY_EXPORT_FUNCTION(aTables, "Export2", 0,
                               "ExportByOrdinal | Export2 was exported.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, kSecretFunction, 0,
            "ModifyDirectoryEntry | kSecretFunction was exported by name.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, kSecretFunctionWithSuffix, 0,
            "ModifyDirectoryEntry | "
            "kSecretFunctionWithSuffix was exported by name.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, MAKEINTRESOURCE(1), SecretFunction1,
            "ModifyDirectoryEntry | "
            "kSecretFunction was not exported by ordinal.\n");
        VERIFY_EXPORT_FUNCTION(
            aTables, MAKEINTRESOURCE(2), SecretFunction2,
            "ModifyDirectoryEntry | "
            "kSecretFunctionWithSuffix was not exported by ordinal.\n");
        return kTestSuccess;
      });
  if (result == kTestFail) {
    return result;
  }

  return kTestSuccess;
}