1 // Copyright (c) 2008, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 #include "client/windows/crash_generation/minidump_generator.h"
31 
32 #include <assert.h>
33 #include <avrfsdk.h>
34 
35 #include <algorithm>
36 #include <iterator>
37 #include <list>
38 #include <vector>
39 
40 #include "client/windows/common/auto_critical_section.h"
41 #include "common/scoped_ptr.h"
42 #include "common/windows/guid_string.h"
43 
44 using std::wstring;
45 
46 namespace {
47 
48 // A helper class used to collect handle operations data. Unlike
49 // |MiniDumpWithHandleData| it records the operations for a single handle value
50 // only, making it possible to include this information to a minidump.
51 class HandleTraceData {
52  public:
53   HandleTraceData();
54   ~HandleTraceData();
55 
56   // Collects the handle operations data and formats a user stream to be added
57   // to the minidump.
58   bool CollectHandleData(HANDLE process_handle,
59                          EXCEPTION_POINTERS* exception_pointers);
60 
61   // Fills the user dump entry with a pointer to the collected handle operations
62   // data. Returns |true| if the entry was initialized successfully, or |false|
63   // if no trace data is available.
64   bool GetUserStream(MINIDUMP_USER_STREAM* user_stream);
65 
66  private:
67   // Reads the exception code from the client process's address space.
68   // This routine assumes that the client process's pointer width matches ours.
69   static bool ReadExceptionCode(HANDLE process_handle,
70                                 EXCEPTION_POINTERS* exception_pointers,
71                                 DWORD* exception_code);
72 
73   // Stores handle operations retrieved by VerifierEnumerateResource().
74   static ULONG CALLBACK RecordHandleOperations(void* resource_description,
75                                                void* enumeration_context,
76                                                ULONG* enumeration_level);
77 
78   // Function pointer type for VerifierEnumerateResource, which is looked up
79   // dynamically.
80   typedef BOOL (WINAPI* VerifierEnumerateResourceType)(
81       HANDLE Process,
82       ULONG Flags,
83       ULONG ResourceType,
84       AVRF_RESOURCE_ENUMERATE_CALLBACK ResourceCallback,
85       PVOID EnumerationContext);
86 
87   // Handle to dynamically loaded verifier.dll.
88   HMODULE verifier_module_;
89 
90   // Pointer to the VerifierEnumerateResource function.
91   VerifierEnumerateResourceType enumerate_resource_;
92 
93   // Handle value to look for.
94   ULONG64 handle_;
95 
96   // List of handle operations for |handle_|.
97   std::list<AVRF_HANDLE_OPERATION> operations_;
98 
99   // Minidump stream data.
100   std::vector<char> stream_;
101 };
102 
HandleTraceData()103 HandleTraceData::HandleTraceData()
104     : verifier_module_(NULL),
105       enumerate_resource_(NULL),
106       handle_(NULL) {
107 }
108 
~HandleTraceData()109 HandleTraceData::~HandleTraceData() {
110   if (verifier_module_) {
111     FreeLibrary(verifier_module_);
112   }
113 }
114 
CollectHandleData(HANDLE process_handle,EXCEPTION_POINTERS * exception_pointers)115 bool HandleTraceData::CollectHandleData(
116     HANDLE process_handle,
117     EXCEPTION_POINTERS* exception_pointers) {
118   DWORD exception_code;
119   if (!ReadExceptionCode(process_handle, exception_pointers, &exception_code)) {
120     return false;
121   }
122 
123   // Verify whether the execption is STATUS_INVALID_HANDLE. Do not record any
124   // handle information if it is a different exception to keep the minidump
125   // small.
126   if (exception_code != STATUS_INVALID_HANDLE) {
127     return true;
128   }
129 
130   // Load verifier!VerifierEnumerateResource() dynamically.
131   verifier_module_ = LoadLibrary(TEXT("verifier.dll"));
132   if (!verifier_module_) {
133     return false;
134   }
135 
136   enumerate_resource_ = reinterpret_cast<VerifierEnumerateResourceType>(
137       GetProcAddress(verifier_module_, "VerifierEnumerateResource"));
138   if (!enumerate_resource_) {
139     return false;
140   }
141 
142   // STATUS_INVALID_HANDLE does not provide the offending handle value in
143   // the exception parameters so we have to guess. At the moment we scan
144   // the handle operations trace looking for the last invalid handle operation
145   // and record only the operations for that handle value.
146   if (enumerate_resource_(process_handle,
147                           0,
148                           AvrfResourceHandleTrace,
149                           &RecordHandleOperations,
150                           this) != ERROR_SUCCESS) {
151     // The handle tracing must have not been enabled.
152     return true;
153   }
154 
155   // Now that |handle_| is initialized, purge all irrelevant operations.
156   std::list<AVRF_HANDLE_OPERATION>::iterator i = operations_.begin();
157   std::list<AVRF_HANDLE_OPERATION>::iterator i_end = operations_.end();
158   while (i != i_end) {
159     if (i->Handle == handle_) {
160       ++i;
161     } else {
162       i = operations_.erase(i);
163     }
164   }
165 
166   // Convert the list of recorded operations to a minidump stream.
167   stream_.resize(sizeof(MINIDUMP_HANDLE_OPERATION_LIST) +
168       sizeof(AVRF_HANDLE_OPERATION) * operations_.size());
169 
170   MINIDUMP_HANDLE_OPERATION_LIST* stream_data =
171       reinterpret_cast<MINIDUMP_HANDLE_OPERATION_LIST*>(
172           &stream_.front());
173   stream_data->SizeOfHeader = sizeof(MINIDUMP_HANDLE_OPERATION_LIST);
174   stream_data->SizeOfEntry = sizeof(AVRF_HANDLE_OPERATION);
175   stream_data->NumberOfEntries = static_cast<ULONG32>(operations_.size());
176   stream_data->Reserved = 0;
177   AVRF_HANDLE_OPERATION* data_iter = reinterpret_cast<AVRF_HANDLE_OPERATION*>(stream_data + 1);
178   for (i = operations_.begin(); i != i_end; i++)
179     *data_iter++ = *i;
180   return true;
181 }
182 
GetUserStream(MINIDUMP_USER_STREAM * user_stream)183 bool HandleTraceData::GetUserStream(MINIDUMP_USER_STREAM* user_stream) {
184   if (stream_.empty()) {
185     return false;
186   } else {
187     user_stream->Type = HandleOperationListStream;
188     user_stream->BufferSize = static_cast<ULONG>(stream_.size());
189     user_stream->Buffer = &stream_.front();
190     return true;
191   }
192 }
193 
ReadExceptionCode(HANDLE process_handle,EXCEPTION_POINTERS * exception_pointers,DWORD * exception_code)194 bool HandleTraceData::ReadExceptionCode(
195     HANDLE process_handle,
196     EXCEPTION_POINTERS* exception_pointers,
197     DWORD* exception_code) {
198   EXCEPTION_POINTERS pointers;
199   if (!ReadProcessMemory(process_handle,
200                          exception_pointers,
201                          &pointers,
202                          sizeof(pointers),
203                          NULL)) {
204     return false;
205   }
206 
207   if (!ReadProcessMemory(process_handle,
208                          pointers.ExceptionRecord,
209                          exception_code,
210                          sizeof(*exception_code),
211                          NULL)) {
212     return false;
213   }
214 
215   return true;
216 }
217 
RecordHandleOperations(void * resource_description,void * enumeration_context,ULONG * enumeration_level)218 ULONG CALLBACK HandleTraceData::RecordHandleOperations(
219     void* resource_description,
220     void* enumeration_context,
221     ULONG* enumeration_level) {
222   AVRF_HANDLE_OPERATION* description =
223       reinterpret_cast<AVRF_HANDLE_OPERATION*>(resource_description);
224   HandleTraceData* self =
225       reinterpret_cast<HandleTraceData*>(enumeration_context);
226 
227   // Remember the last invalid handle operation.
228   if (description->OperationType == OperationDbBADREF) {
229     self->handle_ = description->Handle;
230   }
231 
232   // Record all handle operations.
233   self->operations_.push_back(*description);
234 
235   *enumeration_level = HeapEnumerationEverything;
236   return ERROR_SUCCESS;
237 }
238 
239 }  // namespace
240 
241 namespace google_breakpad {
242 
MinidumpGenerator(const std::wstring & dump_path,const HANDLE process_handle,const DWORD process_id,const DWORD thread_id,const DWORD requesting_thread_id,EXCEPTION_POINTERS * exception_pointers,MDRawAssertionInfo * assert_info,const MINIDUMP_TYPE dump_type,const bool is_client_pointers)243 MinidumpGenerator::MinidumpGenerator(
244     const std::wstring& dump_path,
245     const HANDLE process_handle,
246     const DWORD process_id,
247     const DWORD thread_id,
248     const DWORD requesting_thread_id,
249     EXCEPTION_POINTERS* exception_pointers,
250     MDRawAssertionInfo* assert_info,
251     const MINIDUMP_TYPE dump_type,
252     const bool is_client_pointers)
253     : dbghelp_module_(NULL),
254       rpcrt4_module_(NULL),
255       dump_path_(dump_path),
256       process_handle_(process_handle),
257       process_id_(process_id),
258       thread_id_(thread_id),
259       requesting_thread_id_(requesting_thread_id),
260       exception_pointers_(exception_pointers),
261       assert_info_(assert_info),
262       dump_type_(dump_type),
263       is_client_pointers_(is_client_pointers),
264       dump_file_(INVALID_HANDLE_VALUE),
265       full_dump_file_(INVALID_HANDLE_VALUE),
266       dump_file_is_internal_(false),
267       full_dump_file_is_internal_(false),
268       additional_streams_(NULL),
269       callback_info_(NULL),
270       write_dump_(NULL),
271       create_uuid_(NULL) {
272   InitializeCriticalSection(&module_load_sync_);
273   InitializeCriticalSection(&get_proc_address_sync_);
274 }
275 
~MinidumpGenerator()276 MinidumpGenerator::~MinidumpGenerator() {
277   if (dump_file_is_internal_ && dump_file_ != INVALID_HANDLE_VALUE) {
278     CloseHandle(dump_file_);
279   }
280 
281   if (full_dump_file_is_internal_ && full_dump_file_ != INVALID_HANDLE_VALUE) {
282     CloseHandle(full_dump_file_);
283   }
284 
285   if (dbghelp_module_) {
286     FreeLibrary(dbghelp_module_);
287   }
288 
289   if (rpcrt4_module_) {
290     FreeLibrary(rpcrt4_module_);
291   }
292 
293   DeleteCriticalSection(&get_proc_address_sync_);
294   DeleteCriticalSection(&module_load_sync_);
295 }
296 
WriteMinidump()297 bool MinidumpGenerator::WriteMinidump() {
298   bool full_memory_dump = (dump_type_ & MiniDumpWithFullMemory) != 0;
299   if (dump_file_ == INVALID_HANDLE_VALUE ||
300       (full_memory_dump && full_dump_file_ == INVALID_HANDLE_VALUE)) {
301     return false;
302   }
303 
304   MiniDumpWriteDumpType write_dump = GetWriteDump();
305   if (!write_dump) {
306     return false;
307   }
308 
309   MINIDUMP_EXCEPTION_INFORMATION* dump_exception_pointers = NULL;
310   MINIDUMP_EXCEPTION_INFORMATION dump_exception_info;
311 
312   // Setup the exception information object only if it's a dump
313   // due to an exception.
314   if (exception_pointers_) {
315     dump_exception_pointers = &dump_exception_info;
316     dump_exception_info.ThreadId = thread_id_;
317     dump_exception_info.ExceptionPointers = exception_pointers_;
318     dump_exception_info.ClientPointers = is_client_pointers_;
319   }
320 
321   // Add an MDRawBreakpadInfo stream to the minidump, to provide additional
322   // information about the exception handler to the Breakpad processor.
323   // The information will help the processor determine which threads are
324   // relevant. The Breakpad processor does not require this information but
325   // can function better with Breakpad-generated dumps when it is present.
326   // The native debugger is not harmed by the presence of this information.
327   MDRawBreakpadInfo breakpad_info = {0};
328   if (!is_client_pointers_) {
329     // Set the dump thread id and requesting thread id only in case of
330     // in-process dump generation.
331     breakpad_info.validity = MD_BREAKPAD_INFO_VALID_DUMP_THREAD_ID |
332                              MD_BREAKPAD_INFO_VALID_REQUESTING_THREAD_ID;
333     breakpad_info.dump_thread_id = thread_id_;
334     breakpad_info.requesting_thread_id = requesting_thread_id_;
335   }
336 
337   int additional_streams_count = additional_streams_ ?
338       additional_streams_->UserStreamCount : 0;
339   scoped_array<MINIDUMP_USER_STREAM> user_stream_array(
340       new MINIDUMP_USER_STREAM[3 + additional_streams_count]);
341   user_stream_array[0].Type = MD_BREAKPAD_INFO_STREAM;
342   user_stream_array[0].BufferSize = sizeof(breakpad_info);
343   user_stream_array[0].Buffer = &breakpad_info;
344 
345   MINIDUMP_USER_STREAM_INFORMATION user_streams;
346   user_streams.UserStreamCount = 1;
347   user_streams.UserStreamArray = user_stream_array.get();
348 
349   MDRawAssertionInfo* actual_assert_info = assert_info_;
350   MDRawAssertionInfo client_assert_info = {0};
351 
352   if (assert_info_) {
353     // If the assertion info object lives in the client process,
354     // read the memory of the client process.
355     if (is_client_pointers_) {
356       SIZE_T bytes_read = 0;
357       if (!ReadProcessMemory(process_handle_,
358                              assert_info_,
359                              &client_assert_info,
360                              sizeof(client_assert_info),
361                              &bytes_read)) {
362         if (dump_file_is_internal_)
363           CloseHandle(dump_file_);
364         if (full_dump_file_is_internal_ &&
365             full_dump_file_ != INVALID_HANDLE_VALUE)
366           CloseHandle(full_dump_file_);
367         return false;
368       }
369 
370       if (bytes_read != sizeof(client_assert_info)) {
371         if (dump_file_is_internal_)
372           CloseHandle(dump_file_);
373         if (full_dump_file_is_internal_ &&
374             full_dump_file_ != INVALID_HANDLE_VALUE)
375           CloseHandle(full_dump_file_);
376         return false;
377       }
378 
379       actual_assert_info  = &client_assert_info;
380     }
381 
382     user_stream_array[1].Type = MD_ASSERTION_INFO_STREAM;
383     user_stream_array[1].BufferSize = sizeof(MDRawAssertionInfo);
384     user_stream_array[1].Buffer = actual_assert_info;
385     ++user_streams.UserStreamCount;
386   }
387 
388   if (additional_streams_) {
389     for (size_t i = 0;
390          i < additional_streams_->UserStreamCount;
391          i++, user_streams.UserStreamCount++) {
392       user_stream_array[user_streams.UserStreamCount].Type =
393           additional_streams_->UserStreamArray[i].Type;
394       user_stream_array[user_streams.UserStreamCount].BufferSize =
395           additional_streams_->UserStreamArray[i].BufferSize;
396       user_stream_array[user_streams.UserStreamCount].Buffer =
397           additional_streams_->UserStreamArray[i].Buffer;
398     }
399   }
400 
401   // If the process is terminated by STATUS_INVALID_HANDLE exception store
402   // the trace of operations for the offending handle value. Do nothing special
403   // if the client already requested the handle trace to be stored in the dump.
404   HandleTraceData handle_trace_data;
405   if (exception_pointers_ && (dump_type_ & MiniDumpWithHandleData) == 0) {
406     if (!handle_trace_data.CollectHandleData(process_handle_,
407                                              exception_pointers_)) {
408       if (dump_file_is_internal_)
409         CloseHandle(dump_file_);
410       if (full_dump_file_is_internal_ &&
411           full_dump_file_ != INVALID_HANDLE_VALUE)
412         CloseHandle(full_dump_file_);
413       return false;
414     }
415   }
416 
417   bool result_full_memory = true;
418   if (full_memory_dump) {
419     result_full_memory = write_dump(
420         process_handle_,
421         process_id_,
422         full_dump_file_,
423         static_cast<MINIDUMP_TYPE>((dump_type_ & (~MiniDumpNormal))
424                                     | MiniDumpWithHandleData),
425         exception_pointers_ ? &dump_exception_info : NULL,
426         &user_streams,
427         NULL) != FALSE;
428   }
429 
430   // Add handle operations trace stream to the minidump if it was collected.
431   if (handle_trace_data.GetUserStream(
432           &user_stream_array[user_streams.UserStreamCount])) {
433     ++user_streams.UserStreamCount;
434   }
435 
436   bool result_minidump = write_dump(
437       process_handle_,
438       process_id_,
439       dump_file_,
440       static_cast<MINIDUMP_TYPE>((dump_type_ & (~MiniDumpWithFullMemory))
441                                   | MiniDumpNormal),
442       exception_pointers_ ? &dump_exception_info : NULL,
443       &user_streams,
444       callback_info_) != FALSE;
445 
446   return result_minidump && result_full_memory;
447 }
448 
GenerateDumpFile(wstring * dump_path)449 bool MinidumpGenerator::GenerateDumpFile(wstring* dump_path) {
450   // The dump file was already set by handle or this function was previously
451   // called.
452   if (dump_file_ != INVALID_HANDLE_VALUE) {
453     return false;
454   }
455 
456   wstring dump_file_path;
457   if (!GenerateDumpFilePath(&dump_file_path)) {
458     return false;
459   }
460 
461   dump_file_ = CreateFile(dump_file_path.c_str(),
462                           GENERIC_WRITE,
463                           0,
464                           NULL,
465                           CREATE_NEW,
466                           FILE_ATTRIBUTE_NORMAL,
467                           NULL);
468   if (dump_file_ == INVALID_HANDLE_VALUE) {
469     return false;
470   }
471 
472   dump_file_is_internal_ = true;
473   *dump_path = dump_file_path;
474   return true;
475 }
476 
GenerateFullDumpFile(wstring * full_dump_path)477 bool MinidumpGenerator::GenerateFullDumpFile(wstring* full_dump_path) {
478   // A full minidump was not requested.
479   if ((dump_type_ & MiniDumpWithFullMemory) == 0) {
480     return false;
481   }
482 
483   // The dump file was already set by handle or this function was previously
484   // called.
485   if (full_dump_file_ != INVALID_HANDLE_VALUE) {
486     return false;
487   }
488 
489   wstring full_dump_file_path;
490   if (!GenerateDumpFilePath(&full_dump_file_path)) {
491     return false;
492   }
493   full_dump_file_path.resize(full_dump_file_path.size() - 4);  // strip .dmp
494   full_dump_file_path.append(TEXT("-full.dmp"));
495 
496   full_dump_file_ = CreateFile(full_dump_file_path.c_str(),
497                                GENERIC_WRITE,
498                                0,
499                                NULL,
500                                CREATE_NEW,
501                                FILE_ATTRIBUTE_NORMAL,
502                                NULL);
503   if (full_dump_file_ == INVALID_HANDLE_VALUE) {
504     return false;
505   }
506 
507   full_dump_file_is_internal_ = true;
508   *full_dump_path = full_dump_file_path;
509   return true;
510 }
511 
GetDbghelpModule()512 HMODULE MinidumpGenerator::GetDbghelpModule() {
513   AutoCriticalSection lock(&module_load_sync_);
514   if (!dbghelp_module_) {
515     dbghelp_module_ = LoadLibrary(TEXT("dbghelp.dll"));
516   }
517 
518   return dbghelp_module_;
519 }
520 
GetWriteDump()521 MinidumpGenerator::MiniDumpWriteDumpType MinidumpGenerator::GetWriteDump() {
522   AutoCriticalSection lock(&get_proc_address_sync_);
523   if (!write_dump_) {
524     HMODULE module = GetDbghelpModule();
525     if (module) {
526       FARPROC proc = GetProcAddress(module, "MiniDumpWriteDump");
527       write_dump_ = reinterpret_cast<MiniDumpWriteDumpType>(proc);
528     }
529   }
530 
531   return write_dump_;
532 }
533 
GetRpcrt4Module()534 HMODULE MinidumpGenerator::GetRpcrt4Module() {
535   AutoCriticalSection lock(&module_load_sync_);
536   if (!rpcrt4_module_) {
537     rpcrt4_module_ = LoadLibrary(TEXT("rpcrt4.dll"));
538   }
539 
540   return rpcrt4_module_;
541 }
542 
GetCreateUuid()543 MinidumpGenerator::UuidCreateType MinidumpGenerator::GetCreateUuid() {
544   AutoCriticalSection lock(&module_load_sync_);
545   if (!create_uuid_) {
546     HMODULE module = GetRpcrt4Module();
547     if (module) {
548       FARPROC proc = GetProcAddress(module, "UuidCreate");
549       create_uuid_ = reinterpret_cast<UuidCreateType>(proc);
550     }
551   }
552 
553   return create_uuid_;
554 }
555 
GenerateDumpFilePath(wstring * file_path)556 bool MinidumpGenerator::GenerateDumpFilePath(wstring* file_path) {
557   UUID id = {0};
558 
559   UuidCreateType create_uuid = GetCreateUuid();
560   if (!create_uuid) {
561     return false;
562   }
563 
564   create_uuid(&id);
565   wstring id_str = GUIDString::GUIDToWString(&id);
566 
567   *file_path = dump_path_ + TEXT("\\") + id_str + TEXT(".dmp");
568   return true;
569 }
570 
571 }  // namespace google_breakpad
572