xref: /aosp_15_r20/external/google-breakpad/src/client/solaris/handler/solaris_lwp.cc (revision 9712c20fc9bbfbac4935993a2ca0b3958c5adad2)
1 // Copyright 2007 Google LLC
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 //     * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 //     * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 //     * Neither the name of Google LLC nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 
29 // Author: Alfred Peng
30 
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>  // Must come first
33 #endif
34 
35 #include <dirent.h>
36 #include <elf.h>
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <limits.h>
40 #include <sys/frame.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/wait.h>
44 #include <unistd.h>
45 
46 #include <algorithm>
47 #include <cassert>
48 #include <cstdio>
49 #include <cstdlib>
50 #include <functional>
51 
52 #include "client/solaris/handler/solaris_lwp.h"
53 #include "common/solaris/message_output.h"
54 
55 using namespace google_breakpad;
56 
57 // This unamed namespace contains helper function.
58 namespace {
59 
60 uintptr_t stack_base_address = 0;
61 static const int HEADER_MAX = 2000;
62 static const int MAP_MAX = 1000;
63 
64 // Context information for the callbacks when validating address by listing
65 // modules.
66 struct AddressValidatingContext {
67   uintptr_t address;
68   bool is_mapped;
69 
AddressValidatingContext__anon540bf7bb0111::AddressValidatingContext70   AddressValidatingContext() : address(0UL), is_mapped(false) {
71   }
72 };
73 
74 // Convert from string to int.
LocalAtoi(char * s,int * r)75 static bool LocalAtoi(char* s, int* r) {
76   assert(s != NULL);
77   assert(r != NULL);
78   char* endptr = NULL;
79   int ret = strtol(s, &endptr, 10);
80   if (endptr == s)
81     return false;
82   *r = ret;
83   return true;
84 }
85 
86 // Callback invoked for each mapped module.
87 // It uses the module's adderss range to validate the address.
AddressNotInModuleCallback(const ModuleInfo & module_info,void * context)88 static bool AddressNotInModuleCallback(const ModuleInfo& module_info,
89                                        void* context) {
90   AddressValidatingContext* addr =
91     reinterpret_cast<AddressValidatingContext*>(context);
92   if (addr->is_mapped = ((module_info.start_addr > 0) &&
93                          (addr->address >= module_info.start_addr) &&
94                          (addr->address <= module_info.start_addr +
95                           module_info.size))) {
96     stack_base_address = module_info.start_addr + module_info.size;
97   }
98 
99   return !addr->is_mapped;
100 }
101 
IterateLwpAll(int pid,CallbackParam<LwpidCallback> * callback_param)102 static int IterateLwpAll(int pid,
103                          CallbackParam<LwpidCallback>* callback_param) {
104   char lwp_path[40];
105   DIR* dir;
106   int count = 0;
107 
108   snprintf(lwp_path, sizeof (lwp_path), "/proc/%d/lwp", (int)pid);
109   if ((dir = opendir(lwp_path)) == NULL)
110     return -1;
111 
112   struct dirent* entry = NULL;
113   while ((entry = readdir(dir)) != NULL) {
114     if ((strcmp(entry->d_name, ".") != 0) &&
115         (strcmp(entry->d_name, "..") != 0)) {
116       int lwpid = 0;
117       int last_pid = 0;
118       if (LocalAtoi(entry->d_name, &lwpid) && last_pid != lwpid) {
119         last_pid = lwpid;
120         ++count;
121         if (callback_param &&
122             !(callback_param->call_back)(lwpid, callback_param->context)) {
123           break;
124         }
125       }
126     }
127   }
128 
129   closedir(dir);
130   return count;
131 }
132 
133 #if defined(__i386) && !defined(NO_FRAME_POINTER)
GetNextFrame(void ** last_ebp)134 void* GetNextFrame(void** last_ebp) {
135   void* sp = *last_ebp;
136   if ((unsigned long)sp == (unsigned long)last_ebp)
137     return NULL;
138   if ((unsigned long)sp & (sizeof(void*) - 1))
139     return NULL;
140   if ((unsigned long)sp - (unsigned long)last_ebp > 100000)
141     return NULL;
142   return sp;
143 }
144 #elif defined(__sparc)
GetNextFrame(void * last_ebp)145 void* GetNextFrame(void* last_ebp) {
146   return reinterpret_cast<struct frame*>(last_ebp)->fr_savfp;
147 }
148 #else
GetNextFrame(void ** last_ebp)149 void* GetNextFrame(void** last_ebp) {
150   return reinterpret_cast<void*>(last_ebp);
151 }
152 #endif
153 
154 
155 class AutoCloser {
156  public:
AutoCloser(int fd)157   AutoCloser(int fd) : fd_(fd) {}
~AutoCloser()158   ~AutoCloser() { if (fd_) close(fd_); }
159  private:
160   int fd_;
161 };
162 
163 // Control the execution of the lwp.
164 // Suspend/Resume lwp based on the value of context.
ControlLwp(int lwpid,void * context)165 static bool ControlLwp(int lwpid, void* context) {
166   // The current thread is the one to handle the crash. Ignore it.
167   if (lwpid != pthread_self()) {
168     int ctlfd;
169     char procname[PATH_MAX];
170     bool suspend = *(bool*)context;
171 
172     // Open the /proc/$pid/lwp/$lwpid/lwpctl files
173     snprintf(procname, sizeof (procname), "/proc/self/lwp/%d/lwpctl", lwpid);
174 
175     if ((ctlfd = open(procname, O_WRONLY|O_EXCL)) < 0) {
176       print_message2(2, "failed to open %s in ControlLwp\n", procname);
177       return false;
178     }
179 
180     AutoCloser autocloser(ctlfd);
181 
182     long ctl[2];
183     ctl[0] = suspend ? PCSTOP : PCRUN;
184     ctl[1] = 0;
185     if (write(ctlfd, ctl, sizeof (ctl)) != sizeof (ctl)) {
186       print_message2(2, "failed in lwp %d\n", lwpid);
187       return false;
188     }
189   }
190 
191   return true;
192 }
193 
194 /*
195  * Utility function to read the contents of a file that contains a
196  * prheader_t at the start (/proc/$pid/lstatus or /proc/$pid/lpsinfo).
197  * Return true on success.
198  */
read_lfile(int pid,const char * lname,prheader_t * lhp)199 static bool read_lfile(int pid, const char* lname, prheader_t* lhp) {
200   char lpath[PATH_MAX];
201   struct stat statb;
202   int fd;
203   size_t size;
204 
205   snprintf(lpath, sizeof (lpath), "/proc/%d/%s", pid, lname);
206   if ((fd = open(lpath, O_RDONLY)) < 0) {
207     print_message2(2, "failed to open %s in read_lfile\n", lpath);
208     return false;
209   }
210 
211   AutoCloser autocloser(fd);
212 
213   if (fstat(fd, &statb) != 0)
214     return false;
215 
216   size = statb.st_size;
217   if ((size / sizeof (prheader_t)) + 32 > HEADER_MAX) {
218     print_message1(2, "map size overflow\n");
219     return false;
220   }
221 
222   if (pread(fd, lhp, size, 0) <= sizeof (prheader_t))
223     return false;
224 
225   return true;
226 }
227 
228 }  // namespace
229 
230 namespace google_breakpad {
231 
SolarisLwp(int pid)232 SolarisLwp::SolarisLwp(int pid) : pid_(pid) {
233 }
234 
~SolarisLwp()235 SolarisLwp::~SolarisLwp() {
236 }
237 
ControlAllLwps(bool suspend)238 int SolarisLwp::ControlAllLwps(bool suspend) {
239   CallbackParam<LwpidCallback> callback_param(ControlLwp, &suspend);
240   return IterateLwpAll(pid_, &callback_param);
241 }
242 
GetLwpCount() const243 int SolarisLwp::GetLwpCount() const {
244   return IterateLwpAll(pid_, NULL);
245 }
246 
Lwp_iter_all(int pid,CallbackParam<LwpCallback> * callback_param) const247 int SolarisLwp::Lwp_iter_all(int pid,
248                              CallbackParam<LwpCallback>* callback_param) const {
249   lwpstatus_t* Lsp;
250   lwpstatus_t* sp;
251   prheader_t lphp[HEADER_MAX];
252   prheader_t lhp[HEADER_MAX];
253   prheader_t* Lphp = lphp;
254   prheader_t* Lhp = lhp;
255   lwpsinfo_t* Lpsp;
256   long nstat;
257   long ninfo;
258   int rv = 0;
259 
260   /*
261    * The /proc/pid/lstatus file has the array of lwpstatus_t's and the
262    * /proc/pid/lpsinfo file has the array of lwpsinfo_t's.
263    */
264   if (read_lfile(pid, "lstatus", Lhp) == NULL)
265     return -1;
266   if (read_lfile(pid, "lpsinfo", Lphp) == NULL) {
267     return -1;
268   }
269 
270   Lsp = (lwpstatus_t*)(uintptr_t)(Lhp + 1);
271   Lpsp = (lwpsinfo_t*)(uintptr_t)(Lphp + 1);
272 
273   for (ninfo = Lphp->pr_nent; ninfo != 0; --ninfo) {
274     if (Lpsp->pr_sname != 'Z') {
275       sp = Lsp;
276       Lsp = (lwpstatus_t*)((uintptr_t)Lsp + Lhp->pr_entsize);
277     } else {
278       sp = NULL;
279     }
280     if (callback_param &&
281         !(callback_param->call_back)(sp, callback_param->context))
282       break;
283     ++rv;
284     Lpsp = (lwpsinfo_t*)((uintptr_t)Lpsp + Lphp->pr_entsize);
285   }
286 
287   return rv;
288 }
289 
GetLwpStackBottom(uintptr_t current_esp) const290 uintptr_t SolarisLwp::GetLwpStackBottom(uintptr_t current_esp) const {
291   AddressValidatingContext addr;
292   addr.address = current_esp;
293   CallbackParam<ModuleCallback> callback_param(AddressNotInModuleCallback,
294                                                &addr);
295   ListModules(&callback_param);
296   return stack_base_address;
297 }
298 
GetModuleCount() const299 int SolarisLwp::GetModuleCount() const {
300   return ListModules(NULL);
301 }
302 
ListModules(CallbackParam<ModuleCallback> * callback_param) const303 int SolarisLwp::ListModules(
304     CallbackParam<ModuleCallback>* callback_param) const {
305   const char* maps_path = "/proc/self/map";
306   struct stat status;
307   int fd = 0, num;
308   prmap_t map_array[MAP_MAX];
309   prmap_t* maps = map_array;
310   size_t size;
311 
312   if ((fd = open(maps_path, O_RDONLY)) == -1) {
313     print_message2(2, "failed to open %s in ListModules\n", maps_path);
314     return -1;
315   }
316 
317   AutoCloser autocloser(fd);
318 
319   if (fstat(fd, &status))
320     return -1;
321 
322   /*
323    * Determine number of mappings, this value must be
324    * larger than the actual module count
325    */
326   size = status.st_size;
327   if ((num = (int)(size / sizeof (prmap_t))) > MAP_MAX) {
328     print_message1(2, "map size overflow\n");
329     return -1;
330   }
331 
332   if (read(fd, (void*)maps, size) < 0) {
333     print_message2(2, "failed to read %d\n", fd);
334     return -1;
335   }
336 
337   prmap_t* _maps;
338   int _num;
339   int module_count = 0;
340 
341   /*
342    * Scan each mapping - note it is assummed that the mappings are
343    * presented in order.  We fill holes between mappings.  On intel
344    * the last mapping is usually the data segment of ld.so.1, after
345    * this comes a red zone into which non-fixed mapping won't get
346    * place.  Thus we can simply bail from the loop after seeing the
347    * last mapping.
348    */
349   for (_num = 0, _maps = maps; _num < num; ++_num, ++_maps) {
350     ModuleInfo module;
351     char* name = _maps->pr_mapname;
352 
353     memset(&module, 0, sizeof (module));
354     module.start_addr = _maps->pr_vaddr;
355     module.size = _maps->pr_size;
356     if (strlen(name) > 0) {
357       int objectfd = 0;
358       char path[PATH_MAX];
359       char buf[SELFMAG];
360 
361       snprintf(path, sizeof (path), "/proc/self/object/%s", name);
362       if ((objectfd = open(path, O_RDONLY)) < 0) {
363         print_message1(2, "can't open module file\n");
364         continue;
365       }
366 
367       AutoCloser autocloser(objectfd);
368 
369       if (read(objectfd, buf, SELFMAG) != SELFMAG) {
370         print_message1(2, "can't read module file\n");
371         continue;
372       }
373       if (buf[0] != ELFMAG0 || buf[1] != ELFMAG1 ||
374           buf[2] != ELFMAG2 || buf[3] != ELFMAG3) {
375         continue;
376       }
377 
378       strncpy(module.name, name, sizeof (module.name) - 1);
379       ++module_count;
380     }
381     if (callback_param &&
382         (!callback_param->call_back(module, callback_param->context))) {
383       break;
384     }
385   }
386 
387   return module_count;
388 }
389 
390 // Check if the address is a valid virtual address.
391 // If the address is in any of the mapped modules, we take it as valid.
392 // Otherwise it is invalid.
IsAddressMapped(uintptr_t address) const393 bool SolarisLwp::IsAddressMapped(uintptr_t address) const {
394   AddressValidatingContext addr;
395   addr.address = address;
396   CallbackParam<ModuleCallback> callback_param(AddressNotInModuleCallback,
397                                                &addr);
398   ListModules(&callback_param);
399   return addr.is_mapped;
400 }
401 
402 // We're looking for a ucontext_t as the second parameter
403 // to a signal handler function call.  Luckily, the ucontext_t
404 // has an ebp(fp on SPARC) member which should match the ebp(fp)
405 // pointed to by the ebp(fp) of the signal handler frame.
406 // The Solaris stack looks like this:
407 // http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/lib/libproc/common/Pstack.c#81
FindSigContext(uintptr_t sighandler_ebp,ucontext_t ** sig_ctx)408 bool SolarisLwp::FindSigContext(uintptr_t sighandler_ebp,
409                                 ucontext_t** sig_ctx) {
410   uintptr_t previous_ebp;
411   uintptr_t sig_ebp;
412   const int MAX_STACK_DEPTH = 50;
413   int depth_counter = 0;
414 
415   do {
416 #if TARGET_CPU_SPARC
417     previous_ebp = reinterpret_cast<uintptr_t>(GetNextFrame(
418                                   reinterpret_cast<void*>(sighandler_ebp)));
419     *sig_ctx = reinterpret_cast<ucontext_t*>(sighandler_ebp + sizeof (struct frame));
420     uintptr_t sig_esp = (*sig_ctx)->uc_mcontext.gregs[REG_O6];
421     if (sig_esp < previous_ebp && sig_esp > sighandler_ebp)
422       sig_ebp = (uintptr_t)(((struct frame*)sig_esp)->fr_savfp);
423 
424 #elif TARGET_CPU_X86
425     previous_ebp = reinterpret_cast<uintptr_t>(GetNextFrame(
426                                   reinterpret_cast<void**>(sighandler_ebp)));
427     *sig_ctx = reinterpret_cast<ucontext_t*>(sighandler_ebp + sizeof (struct frame) +
428                                              3 * sizeof(uintptr_t));
429     sig_ebp = (*sig_ctx)->uc_mcontext.gregs[EBP];
430 #endif
431     sighandler_ebp = previous_ebp;
432     depth_counter++;
433   } while(previous_ebp != sig_ebp && sighandler_ebp != 0 &&
434           IsAddressMapped(sighandler_ebp) && depth_counter < MAX_STACK_DEPTH);
435 
436   return previous_ebp == sig_ebp && previous_ebp != 0;
437 }
438 
439 }  // namespace google_breakpad
440