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

base / debug / gdi_debug_util_win.cc [blame]

// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/debug/gdi_debug_util_win.h"

#include <windows.h>

#include <TlHelp32.h>
#include <psapi.h>
#include <stddef.h>
#include <winternl.h>

#include <algorithm>
#include <cmath>
#include <optional>

#include "base/debug/alias.h"
#include "base/logging.h"
#include "base/notreached.h"
#include "base/process/process.h"
#include "base/win/scoped_handle.h"
#include "base/win/win_util.h"
#include "base/win/windows_version.h"

namespace {

// A partial PEB up until GdiSharedHandleTable.
// Derived from the ntdll symbols (ntdll!_PEB).
template <typename PointerType>
struct PartialWinPeb {
  unsigned char InheritedAddressSpace;
  unsigned char ReadImageFileExecOptions;
  unsigned char BeingDebugged;
  unsigned char ImageUsesLargePages : 1;
  unsigned char IsProtectedProcess : 1;
  unsigned char IsLegacyProcess : 1;
  unsigned char IsImageDynamicallyRelocated : 1;
  unsigned char SkipPatchingUser32Forwarders : 1;
  unsigned char IsAppContainer : 1;
  unsigned char IsProtectedProcessLight : 1;
  unsigned char IsLongPathAwareProcess : 1;
  PointerType Mutant;
  PointerType ImageBaseAddress;
  PointerType Ldr;
  PointerType ProcessParamters;
  PointerType SubSystemData;
  PointerType ProcessHeap;
  PointerType FastPebLock;
  PointerType AtlThunkSListPtr;
  PointerType IFEOKey;
  uint32_t ProcessInJob : 1;
  uint32_t ProcessInitializing : 1;
  uint32_t ProcessUsingVEH : 1;
  uint32_t ProcessUsingVCH : 1;
  uint32_t ProcessUsingFTH : 1;
  uint32_t ProcessPreviouslyThrottled : 1;
  uint32_t ProcessCurrentlyThrottled : 1;
  uint32_t ProcessImagesHotPatched : 1;
  PointerType KernelCallbackTable;
  uint32_t SystemReserved;
  uint32_t AtlThunkSListPtr32;
  PointerType ApiSetMap;
  uint32_t TlsExpansionCounter;
  PointerType TlsBitmap;
  uint32_t TlsBitmapBits[2];
  PointerType ReadOnlySharedMemoryBase;
  PointerType HotpatchInformation;
  PointerType ReadOnlyStaticServerData;
  PointerType AnsiCodePageData;
  PointerType OemCodePageData;
  PointerType UnicodeCaseTableData;
  uint32_t NumberOfProcessors;
  uint32_t NtGlobalFlag;
  uint64_t CriticalSectionTimeout;
  PointerType HeapSegmentReserve;
  PointerType HeapSegmentCommit;
  PointerType HeapDeCommitTotalFreeThreshold;
  PointerType HeapDeCommitFreeBlockThreshold;
  uint32_t NumberOfHeaps;
  uint32_t MaximumNumberOfHeaps;
  PointerType ProcessHeaps;
  PointerType GdiSharedHandleTable;
};

// Found from
// https://stackoverflow.com/questions/13905661/how-to-get-list-of-gdi-handles.
enum GdiHandleType : USHORT {
  kDC = 1,
  kRegion = 4,
  kBitmap = 5,
  kPalette = 8,
  kFont = 10,
  kBrush = 16,
  kPen = 48,
};

// Adapted from GDICELL.
template <typename PointerType>
struct GdiTableEntry {
  PointerType pKernelAddress;
  USHORT wProcessId;
  USHORT wCount;
  USHORT wUpper;
  GdiHandleType wType;
  PointerType pUserAddress;
};

// Types and names used for regular processes.
struct RegularProcessTypes {
  using QueryInformationProcessFunc = decltype(NtQueryInformationProcess);
  static const char* query_information_process_name;
  // PROCESS_BASIC_INFORMATION
  struct ProcessBasicInformation {
    PVOID Reserved1;
    PVOID PebBaseAddress;
    PVOID Reserved2[2];
    ULONG_PTR UniqueProcessId;
    PVOID Reserved3;
  };

  using ReadVirtualMemoryFunc = NTSTATUS NTAPI(IN HANDLE ProcessHandle,
                                               IN PVOID BaseAddress,
                                               OUT PVOID Buffer,
                                               IN SIZE_T Size,
                                               OUT PSIZE_T NumberOfBytesRead);
  static const char* read_virtual_memory_func_name;
  using NativePointerType = PVOID;
};

// static
const char* RegularProcessTypes::query_information_process_name =
    "NtQueryInformationProcess";

// static
const char* RegularProcessTypes::read_virtual_memory_func_name =
    "NtReadVirtualMemory";

// Types and names used for WOW based processes.
struct WowProcessTypes {
  // http://crbug.com/972185: Clang doesn't handle PVOID64 correctly, so we use
  // uint64_t as a substitute.

  // NtWow64QueryInformationProcess64 and NtQueryInformationProcess share the
  // same signature.
  using QueryInformationProcessFunc = decltype(NtQueryInformationProcess);
  static const char* query_information_process_name;
  // PROCESS_BASIC_INFORMATION_WOW64
  struct ProcessBasicInformation {
    PVOID Reserved1[2];
    uint64_t PebBaseAddress;
    PVOID Reserved2[4];
    ULONG_PTR UniqueProcessId[2];
    PVOID Reserved3[2];
  };

  using ReadVirtualMemoryFunc = NTSTATUS NTAPI(IN HANDLE ProcessHandle,
                                               IN uint64_t BaseAddress,
                                               OUT PVOID Buffer,
                                               IN ULONG64 Size,
                                               OUT PULONG64 NumberOfBytesRead);
  static const char* read_virtual_memory_func_name;
  using NativePointerType = uint64_t;
};

// static
const char* WowProcessTypes::query_information_process_name =
    "NtWow64QueryInformationProcess64";

// static
const char* WowProcessTypes::read_virtual_memory_func_name =
    "NtWow64ReadVirtualMemory64";

// To prevent from having to write a regular and WOW codepaths that do the same
// thing with different structures and functions, GetGdiTableEntries is
// templated to expect either RegularProcessTypes or WowProcessTypes.
template <typename ProcessType>
std::vector<GdiTableEntry<typename ProcessType::NativePointerType>>
GetGdiTableEntries(const base::Process& process) {
  using GdiTableEntryVector =
      std::vector<GdiTableEntry<typename ProcessType::NativePointerType>>;
  HMODULE ntdll = GetModuleHandle(L"ntdll.dll");
  if (!ntdll)
    return GdiTableEntryVector();

  static auto query_information_process_func =
      reinterpret_cast<typename ProcessType::QueryInformationProcessFunc*>(
          GetProcAddress(ntdll, ProcessType::query_information_process_name));
  if (!query_information_process_func) {
    LOG(ERROR) << ProcessType::query_information_process_name << " Missing";
    return GdiTableEntryVector();
  }

  typename ProcessType::ProcessBasicInformation basic_info;
  NTSTATUS result =
      query_information_process_func(process.Handle(), ProcessBasicInformation,
                                     &basic_info, sizeof(basic_info), nullptr);
  if (result != 0) {
    LOG(ERROR) << ProcessType::query_information_process_name << " Failed "
               << std::hex << result;
    return GdiTableEntryVector();
  }

  static auto read_virtual_mem_func =
      reinterpret_cast<typename ProcessType::ReadVirtualMemoryFunc*>(
          GetProcAddress(ntdll, ProcessType::read_virtual_memory_func_name));
  if (!read_virtual_mem_func) {
    LOG(ERROR) << ProcessType::read_virtual_memory_func_name << " Missing";
    return GdiTableEntryVector();
  }

  PartialWinPeb<typename ProcessType::NativePointerType> peb;
  result = read_virtual_mem_func(process.Handle(), basic_info.PebBaseAddress,
                                 &peb, sizeof(peb), nullptr);
  if (result != 0) {
    LOG(ERROR) << ProcessType::read_virtual_memory_func_name << " PEB Failed "
               << std::hex << result;
    return GdiTableEntryVector();
  }

  // Estimated size derived from address space allocation of the table:
  // Windows 10
  // 32-bit Size: 1052672 bytes
  // 64-bit Size: 1576960 bytes
  // sizeof(GdiTableEntry)
  // 32-bit: 16 bytes
  // 64-bit: 24 bytes
  // Entry Count
  // 32-bit: 65792
  // 64-bit: 65706ish
  // So we'll take a look at 65536 entries since that's the maximum handle count.
  constexpr int kGdiTableEntryCount = 65536;
  GdiTableEntryVector entries;
  entries.resize(kGdiTableEntryCount);
  result = read_virtual_mem_func(
      process.Handle(), peb.GdiSharedHandleTable, &entries[0],
      sizeof(typename GdiTableEntryVector::value_type) * entries.size(),
      nullptr);
  if (result != 0) {
    LOG(ERROR) << ProcessType::read_virtual_memory_func_name
               << " GDI Handle Table Failed " << std::hex << result;
    return GdiTableEntryVector();
  }

  return entries;
}

// Iterates through |gdi_table| and finds handles that belong to |pid|,
// incrementing the appropriate fields in |base::debug::GdiHandleCounts|.
template <typename PointerType>
base::debug::GdiHandleCounts CountHandleTypesFromTable(
    DWORD pid,
    const std::vector<GdiTableEntry<PointerType>>& gdi_table) {
  base::debug::GdiHandleCounts counts{};
  for (const auto& entry : gdi_table) {
    if (entry.wProcessId != pid)
      continue;

    switch (entry.wType & 0x7F) {
      case GdiHandleType::kDC:
        ++counts.dcs;
        break;
      case GdiHandleType::kRegion:
        ++counts.regions;
        break;
      case GdiHandleType::kBitmap:
        ++counts.bitmaps;
        break;
      case GdiHandleType::kPalette:
        ++counts.palettes;
        break;
      case GdiHandleType::kFont:
        ++counts.fonts;
        break;
      case GdiHandleType::kBrush:
        ++counts.brushes;
        break;
      case GdiHandleType::kPen:
        ++counts.pens;
        break;
      default:
        ++counts.unknown;
        break;
    }
  }
  counts.total_tracked = counts.dcs + counts.regions + counts.bitmaps +
                         counts.palettes + counts.fonts + counts.brushes +
                         counts.pens + counts.unknown;
  return counts;
}

template <typename ProcessType>
std::optional<base::debug::GdiHandleCounts> CollectGdiHandleCountsImpl(
    DWORD pid) {
  base::Process process = base::Process::OpenWithExtraPrivileges(pid);
  if (!process.IsValid())
    return std::nullopt;

  std::vector<GdiTableEntry<typename ProcessType::NativePointerType>>
      gdi_entries = GetGdiTableEntries<ProcessType>(process);
  return CountHandleTypesFromTable(pid, gdi_entries);
}

// Returns the GDI Handle counts from the GDI Shared handle table. Empty on
// failure.
std::optional<base::debug::GdiHandleCounts> CollectGdiHandleCounts(DWORD pid) {
  if (base::win::OSInfo::GetInstance()->IsWowX86OnAMD64()) {
    return CollectGdiHandleCountsImpl<WowProcessTypes>(pid);
  }

  return CollectGdiHandleCountsImpl<RegularProcessTypes>(pid);
}

constexpr size_t kLotsOfMemory = 1500 * 1024 * 1024;  // 1.5GB

NOINLINE HANDLE GetToolhelpSnapshot() {
  HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  CHECK_NE(INVALID_HANDLE_VALUE, snapshot);
  return snapshot;
}

NOINLINE void GetFirstProcess(HANDLE snapshot, PROCESSENTRY32* proc_entry) {
  proc_entry->dwSize = sizeof(PROCESSENTRY32);
  CHECK(Process32First(snapshot, proc_entry));
}

NOINLINE void CrashIfExcessiveHandles(DWORD num_gdi_handles) {
  // By default, Windows 10 allows a max of 10,000 GDI handles per process.
  // Number found by inspecting
  //
  // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\
  //    CurrentVersion\Windows\GDIProcessHandleQuota
  //
  // on a Windows 10 laptop.
  static constexpr DWORD kLotsOfHandles = 9990;
  CHECK_LE(num_gdi_handles, kLotsOfHandles);
}

NOINLINE void CrashIfPagefileUsageTooLarge(
    const PROCESS_MEMORY_COUNTERS_EX& pmc) {
  CHECK_LE(pmc.PagefileUsage, kLotsOfMemory);
}

NOINLINE void CrashIfPrivateUsageTooLarge(
    const PROCESS_MEMORY_COUNTERS_EX& pmc) {
  CHECK_LE(pmc.PrivateUsage, kLotsOfMemory);
}

NOINLINE void CrashIfCannotAllocateSmallBitmap(BITMAPINFOHEADER* header,
                                               HANDLE shared_section) {
  void* small_data = nullptr;
  base::debug::Alias(&small_data);
  header->biWidth = 5;
  header->biHeight = -5;
  HBITMAP small_bitmap =
      CreateDIBSection(nullptr, reinterpret_cast<BITMAPINFO*>(&header), 0,
                       &small_data, shared_section, 0);
  CHECK(small_bitmap != nullptr);
  DeleteObject(small_bitmap);
}

NOINLINE void GetProcessMemoryInfo(PROCESS_MEMORY_COUNTERS_EX* pmc) {
  pmc->cb = sizeof(*pmc);
  CHECK(GetProcessMemoryInfo(GetCurrentProcess(),
                             reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(pmc),
                             sizeof(*pmc)));
}

NOINLINE DWORD GetNumGdiHandles() {
  DWORD num_gdi_handles = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS);
  if (num_gdi_handles == 0) {
    DWORD get_gui_resources_error = GetLastError();
    base::debug::Alias(&get_gui_resources_error);
    NOTREACHED();
  }
  return num_gdi_handles;
}

void CollectChildGDIUsageAndDie(DWORD parent_pid) {
  HANDLE snapshot = GetToolhelpSnapshot();

  int total_process_count = 0;
  base::debug::Alias(&total_process_count);
  DWORD total_peak_gdi_count = 0;
  base::debug::Alias(&total_peak_gdi_count);
  DWORD total_gdi_count = 0;
  base::debug::Alias(&total_gdi_count);
  DWORD total_user_count = 0;
  base::debug::Alias(&total_user_count);

  int child_count = 0;
  base::debug::Alias(&child_count);
  DWORD peak_gdi_count = 0;
  base::debug::Alias(&peak_gdi_count);
  DWORD sum_gdi_count = 0;
  base::debug::Alias(&sum_gdi_count);
  DWORD sum_user_count = 0;
  base::debug::Alias(&sum_user_count);

  PROCESSENTRY32 proc_entry = {};
  GetFirstProcess(snapshot, &proc_entry);

  do {
    base::win::ScopedHandle process(
        OpenProcess(PROCESS_QUERY_INFORMATION,
                    FALSE,
                    proc_entry.th32ProcessID));
    if (!process.is_valid())
      continue;

    DWORD num_gdi_handles = GetGuiResources(process.get(), GR_GDIOBJECTS);
    DWORD num_user_handles = GetGuiResources(process.get(), GR_USEROBJECTS);

    // Compute sum and peak counts for all processes.
    ++total_process_count;
    total_user_count += num_user_handles;
    total_gdi_count += num_gdi_handles;
    total_peak_gdi_count = std::max(total_peak_gdi_count, num_gdi_handles);

    if (parent_pid != proc_entry.th32ParentProcessID)
      continue;

    // Compute sum and peak counts for child processes.
    ++child_count;
    sum_user_count += num_user_handles;
    sum_gdi_count += num_gdi_handles;
    peak_gdi_count = std::max(peak_gdi_count, num_gdi_handles);
  } while (Process32Next(snapshot, &proc_entry));

  CloseHandle(snapshot);
  NOTREACHED();
}

}  // namespace

namespace base {
namespace debug {

void CollectGDIUsageAndDie(BITMAPINFOHEADER* header, HANDLE shared_section) {
  // Make sure parameters are saved in the minidump.
  DWORD last_error = GetLastError();
  bool is_gdi_available = base::win::IsUser32AndGdi32Available();

  LONG width = header ? header->biWidth : 0;
  LONG height = header ? header->biHeight : 0;

  base::debug::Alias(&last_error);
  base::debug::Alias(&is_gdi_available);
  base::debug::Alias(&width);
  base::debug::Alias(&height);
  base::debug::Alias(&shared_section);

  DWORD num_user_handles = GetGuiResources(GetCurrentProcess(), GR_USEROBJECTS);
  DWORD num_gdi_handles = GetNumGdiHandles();
  DWORD peak_gdi_handles =
      GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS_PEAK);
  DWORD num_global_gdi_handles = GetGuiResources(GR_GLOBAL, GR_GDIOBJECTS);
  DWORD num_global_user_handles = GetGuiResources(GR_GLOBAL, GR_USEROBJECTS);

  base::debug::Alias(&num_gdi_handles);
  base::debug::Alias(&num_user_handles);
  base::debug::Alias(&peak_gdi_handles);
  base::debug::Alias(&num_global_gdi_handles);
  base::debug::Alias(&num_global_user_handles);

  std::optional<GdiHandleCounts> optional_handle_counts =
      CollectGdiHandleCounts(GetCurrentProcessId());
  bool handle_counts_set = optional_handle_counts.has_value();
  GdiHandleCounts handle_counts =
      optional_handle_counts.value_or(GdiHandleCounts());
  int tracked_dcs = handle_counts.dcs;
  int tracked_regions = handle_counts.regions;
  int tracked_bitmaps = handle_counts.bitmaps;
  int tracked_palettes = handle_counts.palettes;
  int tracked_fonts = handle_counts.fonts;
  int tracked_brushes = handle_counts.brushes;
  int tracked_pens = handle_counts.pens;
  int tracked_unknown_handles = handle_counts.unknown;
  int tracked_total = handle_counts.total_tracked;

  base::debug::Alias(&handle_counts_set);
  base::debug::Alias(&tracked_dcs);
  base::debug::Alias(&tracked_regions);
  base::debug::Alias(&tracked_bitmaps);
  base::debug::Alias(&tracked_palettes);
  base::debug::Alias(&tracked_fonts);
  base::debug::Alias(&tracked_brushes);
  base::debug::Alias(&tracked_pens);
  base::debug::Alias(&tracked_unknown_handles);
  base::debug::Alias(&tracked_total);

  CrashIfExcessiveHandles(num_gdi_handles);

  PROCESS_MEMORY_COUNTERS_EX pmc;
  GetProcessMemoryInfo(&pmc);
  CrashIfPagefileUsageTooLarge(pmc);
  CrashIfPrivateUsageTooLarge(pmc);

  if (std::abs(height) * width > 100) {
    // Huh, that's weird.  We don't have crazy handle count, we don't have
    // ridiculous memory usage. Try to allocate a small bitmap and see if that
    // fails too.
    CrashIfCannotAllocateSmallBitmap(header, shared_section);
  }
  // Maybe the child processes are the ones leaking GDI or USER resouces.
  CollectChildGDIUsageAndDie(GetCurrentProcessId());
}

GdiHandleCounts GetGDIHandleCountsInCurrentProcessForTesting() {
  std::optional<GdiHandleCounts> handle_counts =
      CollectGdiHandleCounts(GetCurrentProcessId());
  DCHECK(handle_counts.has_value());
  return handle_counts.value_or(GdiHandleCounts());
}

}  // namespace debug
}  // namespace base