Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / breakpad / src / client / linux / minidump_writer / linux_dumper.cc
1 // Copyright (c) 2010, 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 // linux_dumper.cc: Implement google_breakpad::LinuxDumper.
31 // See linux_dumper.h for details.
32
33 // This code deals with the mechanics of getting information about a crashed
34 // process. Since this code may run in a compromised address space, the same
35 // rules apply as detailed at the top of minidump_writer.h: no libc calls and
36 // use the alternative allocator.
37
38 #include "client/linux/minidump_writer/linux_dumper.h"
39
40 #include <assert.h>
41 #include <elf.h>
42 #include <fcntl.h>
43 #include <limits.h>
44 #include <stddef.h>
45 #include <string.h>
46
47 #include "client/linux/minidump_writer/line_reader.h"
48 #include "common/linux/elfutils.h"
49 #include "common/linux/file_id.h"
50 #include "common/linux/linux_libc_support.h"
51 #include "common/linux/memory_mapped_file.h"
52 #include "common/linux/safe_readlink.h"
53 #include "third_party/lss/linux_syscall_support.h"
54
55 static const char kMappedFileUnsafePrefix[] = "/dev/";
56 static const char kDeletedSuffix[] = " (deleted)";
57 static const char kReservedFlags[] = " ---p";
58
59 inline static bool IsMappedFileOpenUnsafe(
60     const google_breakpad::MappingInfo& mapping) {
61   // It is unsafe to attempt to open a mapped file that lives under /dev,
62   // because the semantics of the open may be driver-specific so we'd risk
63   // hanging the crash dumper. And a file in /dev/ almost certainly has no
64   // ELF file identifier anyways.
65   return my_strncmp(mapping.name,
66                     kMappedFileUnsafePrefix,
67                     sizeof(kMappedFileUnsafePrefix) - 1) == 0;
68 }
69
70 namespace google_breakpad {
71
72 // All interesting auvx entry types are below AT_SYSINFO_EHDR
73 #define AT_MAX AT_SYSINFO_EHDR
74
75 LinuxDumper::LinuxDumper(pid_t pid)
76     : pid_(pid),
77       crash_address_(0),
78       crash_signal_(0),
79       crash_thread_(pid),
80       threads_(&allocator_, 8),
81       mappings_(&allocator_),
82       auxv_(&allocator_, AT_MAX + 1) {
83   // The passed-in size to the constructor (above) is only a hint.
84   // Must call .resize() to do actual initialization of the elements.
85   auxv_.resize(AT_MAX + 1);
86 }
87
88 LinuxDumper::~LinuxDumper() {
89 }
90
91 bool LinuxDumper::Init() {
92   return ReadAuxv() && EnumerateThreads() && EnumerateMappings();
93 }
94
95 bool
96 LinuxDumper::ElfFileIdentifierForMapping(const MappingInfo& mapping,
97                                          bool member,
98                                          unsigned int mapping_id,
99                                          uint8_t identifier[sizeof(MDGUID)]) {
100   assert(!member || mapping_id < mappings_.size());
101   my_memset(identifier, 0, sizeof(MDGUID));
102   if (IsMappedFileOpenUnsafe(mapping))
103     return false;
104
105   // Special-case linux-gate because it's not a real file.
106   if (my_strcmp(mapping.name, kLinuxGateLibraryName) == 0) {
107     void* linux_gate = NULL;
108     if (pid_ == sys_getpid()) {
109       linux_gate = reinterpret_cast<void*>(mapping.start_addr);
110     } else {
111       linux_gate = allocator_.Alloc(mapping.size);
112       CopyFromProcess(linux_gate, pid_,
113                       reinterpret_cast<const void*>(mapping.start_addr),
114                       mapping.size);
115     }
116     return FileID::ElfFileIdentifierFromMappedFile(linux_gate, identifier);
117   }
118
119   char filename[NAME_MAX];
120   size_t filename_len = my_strlen(mapping.name);
121   if (filename_len >= NAME_MAX) {
122     assert(false);
123     return false;
124   }
125   my_memcpy(filename, mapping.name, filename_len);
126   filename[filename_len] = '\0';
127   bool filename_modified = HandleDeletedFileInMapping(filename);
128
129   MemoryMappedFile mapped_file(filename, mapping.offset);
130   if (!mapped_file.data() || mapped_file.size() < SELFMAG)
131     return false;
132
133   bool success =
134       FileID::ElfFileIdentifierFromMappedFile(mapped_file.data(), identifier);
135   if (success && member && filename_modified) {
136     mappings_[mapping_id]->name[filename_len -
137                                 sizeof(kDeletedSuffix) + 1] = '\0';
138   }
139
140   return success;
141 }
142
143 namespace {
144 bool ElfFileSoNameFromMappedFile(
145     const void* elf_base, char* soname, size_t soname_size) {
146   if (!IsValidElf(elf_base)) {
147     // Not ELF
148     return false;
149   }
150
151   const void* segment_start;
152   size_t segment_size;
153   int elf_class;
154   if (!FindElfSection(elf_base, ".dynamic", SHT_DYNAMIC,
155                       &segment_start, &segment_size, &elf_class)) {
156     // No dynamic section
157     return false;
158   }
159
160   const void* dynstr_start;
161   size_t dynstr_size;
162   if (!FindElfSection(elf_base, ".dynstr", SHT_STRTAB,
163                       &dynstr_start, &dynstr_size, &elf_class)) {
164     // No dynstr section
165     return false;
166   }
167
168   const ElfW(Dyn)* dynamic = static_cast<const ElfW(Dyn)*>(segment_start);
169   size_t dcount = segment_size / sizeof(ElfW(Dyn));
170   for (const ElfW(Dyn)* dyn = dynamic; dyn < dynamic + dcount; ++dyn) {
171     if (dyn->d_tag == DT_SONAME) {
172       const char* dynstr = static_cast<const char*>(dynstr_start);
173       if (dyn->d_un.d_val >= dynstr_size) {
174         // Beyond the end of the dynstr section
175         return false;
176       }
177       const char* str = dynstr + dyn->d_un.d_val;
178       const size_t maxsize = dynstr_size - dyn->d_un.d_val;
179       my_strlcpy(soname, str, maxsize < soname_size ? maxsize : soname_size);
180       return true;
181     }
182   }
183
184   // Did not find SONAME
185   return false;
186 }
187 }  // namespace
188
189 // static
190 bool LinuxDumper::ElfFileSoName(
191     const MappingInfo& mapping, char* soname, size_t soname_size) {
192   if (IsMappedFileOpenUnsafe(mapping)) {
193     // Not safe
194     return false;
195   }
196
197   char filename[NAME_MAX];
198   size_t filename_len = my_strlen(mapping.name);
199   if (filename_len >= NAME_MAX) {
200     assert(false);
201     // name too long
202     return false;
203   }
204
205   my_memcpy(filename, mapping.name, filename_len);
206   filename[filename_len] = '\0';
207
208   MemoryMappedFile mapped_file(filename, mapping.offset);
209   if (!mapped_file.data() || mapped_file.size() < SELFMAG) {
210     // mmap failed
211     return false;
212   }
213
214   return ElfFileSoNameFromMappedFile(mapped_file.data(), soname, soname_size);
215 }
216
217 bool LinuxDumper::ReadAuxv() {
218   char auxv_path[NAME_MAX];
219   if (!BuildProcPath(auxv_path, pid_, "auxv")) {
220     return false;
221   }
222
223   int fd = sys_open(auxv_path, O_RDONLY, 0);
224   if (fd < 0) {
225     return false;
226   }
227
228   elf_aux_entry one_aux_entry;
229   bool res = false;
230   while (sys_read(fd,
231                   &one_aux_entry,
232                   sizeof(elf_aux_entry)) == sizeof(elf_aux_entry) &&
233          one_aux_entry.a_type != AT_NULL) {
234     if (one_aux_entry.a_type <= AT_MAX) {
235       auxv_[one_aux_entry.a_type] = one_aux_entry.a_un.a_val;
236       res = true;
237     }
238   }
239   sys_close(fd);
240   return res;
241 }
242
243 bool LinuxDumper::EnumerateMappings() {
244   char maps_path[NAME_MAX];
245   if (!BuildProcPath(maps_path, pid_, "maps"))
246     return false;
247
248   // linux_gate_loc is the beginning of the kernel's mapping of
249   // linux-gate.so in the process.  It doesn't actually show up in the
250   // maps list as a filename, but it can be found using the AT_SYSINFO_EHDR
251   // aux vector entry, which gives the information necessary to special
252   // case its entry when creating the list of mappings.
253   // See http://www.trilithium.com/johan/2005/08/linux-gate/ for more
254   // information.
255   const void* linux_gate_loc =
256       reinterpret_cast<void *>(auxv_[AT_SYSINFO_EHDR]);
257   // Although the initial executable is usually the first mapping, it's not
258   // guaranteed (see http://crosbug.com/25355); therefore, try to use the
259   // actual entry point to find the mapping.
260   const void* entry_point_loc = reinterpret_cast<void *>(auxv_[AT_ENTRY]);
261
262   const int fd = sys_open(maps_path, O_RDONLY, 0);
263   if (fd < 0)
264     return false;
265   LineReader* const line_reader = new(allocator_) LineReader(fd);
266
267   const char* line;
268   unsigned line_len;
269   while (line_reader->GetNextLine(&line, &line_len)) {
270     uintptr_t start_addr, end_addr, offset;
271
272     const char* i1 = my_read_hex_ptr(&start_addr, line);
273     if (*i1 == '-') {
274       const char* i2 = my_read_hex_ptr(&end_addr, i1 + 1);
275       if (*i2 == ' ') {
276         bool exec = (*(i2 + 3) == 'x');
277         const char* i3 = my_read_hex_ptr(&offset, i2 + 6 /* skip ' rwxp ' */);
278         if (*i3 == ' ') {
279           const char* name = NULL;
280           // Only copy name if the name is a valid path name, or if
281           // it's the VDSO image.
282           if (((name = my_strchr(line, '/')) == NULL) &&
283               linux_gate_loc &&
284               reinterpret_cast<void*>(start_addr) == linux_gate_loc) {
285             name = kLinuxGateLibraryName;
286             offset = 0;
287           }
288           // Merge adjacent mappings with the same name into one module,
289           // assuming they're a single library mapped by the dynamic linker
290           if (name && !mappings_.empty()) {
291             MappingInfo* module = mappings_.back();
292             if ((start_addr == module->start_addr + module->size) &&
293                 (my_strlen(name) == my_strlen(module->name)) &&
294                 (my_strncmp(name, module->name, my_strlen(name)) == 0)) {
295               module->size = end_addr - module->start_addr;
296               line_reader->PopLine(line_len);
297               continue;
298             }
299           }
300           // Also merge mappings that result from address ranges that the
301           // linker reserved but which a loaded library did not use. These
302           // appear as an anonymous private mapping with no access flags set
303           // and which directly follow an executable mapping.
304           if (!name && !mappings_.empty()) {
305             MappingInfo* module = mappings_.back();
306             if ((start_addr == module->start_addr + module->size) &&
307                 module->exec &&
308                 module->name[0] == '/' &&
309                 offset == 0 && my_strncmp(i2,
310                                           kReservedFlags,
311                                           sizeof(kReservedFlags) - 1) == 0) {
312               module->size = end_addr - module->start_addr;
313               line_reader->PopLine(line_len);
314               continue;
315             }
316           }
317           MappingInfo* const module = new(allocator_) MappingInfo;
318           my_memset(module, 0, sizeof(MappingInfo));
319           module->start_addr = start_addr;
320           module->size = end_addr - start_addr;
321           module->offset = offset;
322           module->exec = exec;
323           if (name != NULL) {
324             const unsigned l = my_strlen(name);
325             if (l < sizeof(module->name))
326               my_memcpy(module->name, name, l);
327           }
328           // If this is the entry-point mapping, and it's not already the
329           // first one, then we need to make it be first.  This is because
330           // the minidump format assumes the first module is the one that
331           // corresponds to the main executable (as codified in
332           // processor/minidump.cc:MinidumpModuleList::GetMainModule()).
333           if (entry_point_loc &&
334               (entry_point_loc >=
335                   reinterpret_cast<void*>(module->start_addr)) &&
336               (entry_point_loc <
337                   reinterpret_cast<void*>(module->start_addr+module->size)) &&
338               !mappings_.empty()) {
339             // push the module onto the front of the list.
340             mappings_.resize(mappings_.size() + 1);
341             for (size_t idx = mappings_.size() - 1; idx > 0; idx--)
342               mappings_[idx] = mappings_[idx - 1];
343             mappings_[0] = module;
344           } else {
345             mappings_.push_back(module);
346           }
347         }
348       }
349     }
350     line_reader->PopLine(line_len);
351   }
352
353   sys_close(fd);
354
355   return !mappings_.empty();
356 }
357
358 // Get information about the stack, given the stack pointer. We don't try to
359 // walk the stack since we might not have all the information needed to do
360 // unwind. So we just grab, up to, 32k of stack.
361 bool LinuxDumper::GetStackInfo(const void** stack, size_t* stack_len,
362                                uintptr_t int_stack_pointer) {
363   // Move the stack pointer to the bottom of the page that it's in.
364   const uintptr_t page_size = getpagesize();
365
366   uint8_t* const stack_pointer =
367       reinterpret_cast<uint8_t*>(int_stack_pointer & ~(page_size - 1));
368
369   // The number of bytes of stack which we try to capture.
370   static const ptrdiff_t kStackToCapture = 32 * 1024;
371
372   const MappingInfo* mapping = FindMapping(stack_pointer);
373   if (!mapping)
374     return false;
375   const ptrdiff_t offset = stack_pointer -
376       reinterpret_cast<uint8_t*>(mapping->start_addr);
377   const ptrdiff_t distance_to_end =
378       static_cast<ptrdiff_t>(mapping->size) - offset;
379   *stack_len = distance_to_end > kStackToCapture ?
380       kStackToCapture : distance_to_end;
381   *stack = stack_pointer;
382   return true;
383 }
384
385 // Find the mapping which the given memory address falls in.
386 const MappingInfo* LinuxDumper::FindMapping(const void* address) const {
387   const uintptr_t addr = (uintptr_t) address;
388
389   for (size_t i = 0; i < mappings_.size(); ++i) {
390     const uintptr_t start = static_cast<uintptr_t>(mappings_[i]->start_addr);
391     if (addr >= start && addr - start < mappings_[i]->size)
392       return mappings_[i];
393   }
394
395   return NULL;
396 }
397
398 bool LinuxDumper::HandleDeletedFileInMapping(char* path) const {
399   static const size_t kDeletedSuffixLen = sizeof(kDeletedSuffix) - 1;
400
401   // Check for ' (deleted)' in |path|.
402   // |path| has to be at least as long as "/x (deleted)".
403   const size_t path_len = my_strlen(path);
404   if (path_len < kDeletedSuffixLen + 2)
405     return false;
406   if (my_strncmp(path + path_len - kDeletedSuffixLen, kDeletedSuffix,
407                  kDeletedSuffixLen) != 0) {
408     return false;
409   }
410
411   // Check |path| against the /proc/pid/exe 'symlink'.
412   char exe_link[NAME_MAX];
413   char new_path[NAME_MAX];
414   if (!BuildProcPath(exe_link, pid_, "exe"))
415     return false;
416   if (!SafeReadLink(exe_link, new_path))
417     return false;
418   if (my_strcmp(path, new_path) != 0)
419     return false;
420
421   // Check to see if someone actually named their executable 'foo (deleted)'.
422   struct kernel_stat exe_stat;
423   struct kernel_stat new_path_stat;
424   if (sys_stat(exe_link, &exe_stat) == 0 &&
425       sys_stat(new_path, &new_path_stat) == 0 &&
426       exe_stat.st_dev == new_path_stat.st_dev &&
427       exe_stat.st_ino == new_path_stat.st_ino) {
428     return false;
429   }
430
431   my_memcpy(path, exe_link, NAME_MAX);
432   return true;
433 }
434
435 }  // namespace google_breakpad