1 /*
   2  * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 #include "libproc_impl.h"
  25 
  26 static const char* alt_root = NULL;
  27 static int alt_root_len = -1;
  28 
  29 #define SA_ALTROOT "SA_ALTROOT"
  30 
  31 off_t ltell(int fd) {
  32   return lseek(fd, 0, SEEK_CUR);
  33 }
  34 
  35 static void init_alt_root() {
  36   if (alt_root_len == -1) {
  37     alt_root = getenv(SA_ALTROOT);
  38     if (alt_root) {
  39       alt_root_len = strlen(alt_root);
  40     } else {
  41       alt_root_len = 0;
  42     }
  43   }
  44 }
  45 
  46 int pathmap_open(const char* name) {
  47   int fd;
  48   char alt_path[PATH_MAX + 1];
  49 
  50   init_alt_root();
  51 
  52   if (alt_root_len > 0) {
  53     strcpy(alt_path, alt_root);
  54     strcat(alt_path, name);
  55     fd = open(alt_path, O_RDONLY);
  56     if (fd >= 0) {
  57       print_debug("path %s substituted for %s\n", alt_path, name);
  58       return fd;
  59     }
  60 
  61     if (strrchr(name, '/')) {
  62       strcpy(alt_path, alt_root);
  63       strcat(alt_path, strrchr(name, '/'));
  64       fd = open(alt_path, O_RDONLY);
  65       if (fd >= 0) {
  66         print_debug("path %s substituted for %s\n", alt_path, name);
  67         return fd;
  68       }
  69     }
  70   } else {
  71     fd = open(name, O_RDONLY);
  72     if (fd >= 0) {
  73       return fd;
  74     }
  75   }
  76   return -1;
  77 }
  78 
  79 static bool _libsaproc_debug;
  80 
  81 void print_debug(const char* format,...) {
  82   if (_libsaproc_debug) {
  83     va_list alist;
  84 
  85     va_start(alist, format);
  86     fputs("libsaproc DEBUG: ", stderr);
  87     vfprintf(stderr, format, alist);
  88     va_end(alist);
  89   }
  90 }
  91 
  92 void print_error(const char* format,...) {
  93   va_list alist;
  94   va_start(alist, format);
  95   fputs("ERROR: ", stderr);
  96   vfprintf(stderr, format, alist);
  97   va_end(alist);
  98 }
  99 
 100 bool is_debug() {
 101   return _libsaproc_debug;
 102 }
 103 
 104 #ifdef __APPLE__
 105 // get arch offset in file
 106 bool get_arch_off(int fd, cpu_type_t cputype, off_t *offset) {
 107   struct fat_header fatheader;
 108   struct fat_arch fatarch;
 109   off_t img_start = 0;
 110 
 111   off_t pos = ltell(fd);
 112   if (read(fd, (void *)&fatheader, sizeof(struct fat_header)) != sizeof(struct fat_header)) {
 113     return false;
 114   }
 115   if (fatheader.magic == FAT_CIGAM) {
 116     int i;
 117     for (i = 0; i < ntohl(fatheader.nfat_arch); i++) {
 118       if (read(fd, (void *)&fatarch, sizeof(struct fat_arch)) != sizeof(struct fat_arch)) {
 119         return false;
 120       }
 121       if (ntohl(fatarch.cputype) == cputype) {
 122         print_debug("fat offset=%x\n", ntohl(fatarch.offset));
 123         img_start = ntohl(fatarch.offset);
 124         break;
 125       }
 126     }
 127     if (img_start == 0) {
 128       return false;
 129     }
 130   }
 131   lseek(fd, pos, SEEK_SET);
 132   *offset = img_start;
 133   return true;
 134 }
 135 
 136 bool is_macho_file(int fd) {
 137   mach_header_64 fhdr;
 138   off_t x86_64_off;
 139 
 140   if (fd < 0) {
 141     print_debug("Invalid file handle passed to is_macho_file\n");
 142     return false;
 143   }
 144 
 145   off_t pos = ltell(fd);
 146   // check fat header
 147   if (!get_arch_off(fd, CPU_TYPE_X86_64, &x86_64_off)) {
 148     print_debug("failed to get fat header\n");
 149     return false;
 150   }
 151   lseek(fd, x86_64_off, SEEK_SET);
 152   if (read(fd, (void *)&fhdr, sizeof(mach_header_64)) != sizeof(mach_header_64)) {
 153      return false;
 154   }
 155   lseek(fd, pos, SEEK_SET);               // restore
 156   print_debug("fhdr.magic %x\n", fhdr.magic);
 157   return (fhdr.magic == MH_MAGIC_64 || fhdr.magic == MH_CIGAM_64);
 158 }
 159 
 160 #endif //__APPLE__
 161 
 162 // initialize libproc
 163 bool init_libproc(bool debug) {
 164    _libsaproc_debug = debug;
 165 #ifndef __APPLE__
 166    // initialize the thread_db library
 167    if (td_init() != TD_OK) {
 168      print_debug("libthread_db's td_init failed\n");
 169      return false;
 170    }
 171 #endif // __APPLE__
 172    return true;
 173 }
 174 
 175 void destroy_lib_info(struct ps_prochandle* ph) {
 176   lib_info* lib = ph->libs;
 177   while (lib) {
 178     lib_info* next = lib->next;
 179     if (lib->symtab) {
 180       destroy_symtab(lib->symtab);
 181     }
 182     free(lib);
 183     lib = next;
 184   }
 185 }
 186 
 187 void destroy_thread_info(struct ps_prochandle* ph) {
 188   sa_thread_info* thr = ph->threads;
 189   while (thr) {
 190     sa_thread_info* n = thr->next;
 191     free(thr);
 192     thr = n;
 193   }
 194 }
 195 
 196 // ps_prochandle cleanup
 197 void Prelease(struct ps_prochandle* ph) {
 198   // do the "derived class" clean-up first
 199   ph->ops->release(ph);
 200   destroy_lib_info(ph);
 201   destroy_thread_info(ph);
 202   free(ph);
 203 }
 204 
 205 lib_info* add_lib_info(struct ps_prochandle* ph, const char* libname, uintptr_t base) {
 206   return add_lib_info_fd(ph, libname, -1, base);
 207 }
 208 
 209 lib_info* add_lib_info_fd(struct ps_prochandle* ph, const char* libname, int fd, uintptr_t base) {
 210    lib_info* newlib;
 211   print_debug("add_lib_info_fd %s\n", libname);
 212 
 213   if ( (newlib = (lib_info*) calloc(1, sizeof(struct lib_info))) == NULL) {
 214     print_debug("can't allocate memory for lib_info\n");
 215     return NULL;
 216   }
 217 
 218   strncpy(newlib->name, libname, sizeof(newlib->name));
 219   newlib->base = base;
 220 
 221   if (fd == -1) {
 222     if ( (newlib->fd = pathmap_open(newlib->name)) < 0) {
 223       print_debug("can't open shared object %s\n", newlib->name);
 224       free(newlib);
 225       return NULL;
 226     }
 227   } else {
 228     newlib->fd = fd;
 229   }
 230 
 231 #ifdef __APPLE__
 232   // check whether we have got an Macho file.
 233   if (is_macho_file(newlib->fd) == false) {
 234     close(newlib->fd);
 235     free(newlib);
 236     print_debug("not a mach-o file\n");
 237     return NULL;
 238   }
 239 #else
 240   // check whether we have got an ELF file. /proc/<pid>/map
 241   // gives out all file mappings and not just shared objects
 242   if (is_elf_file(newlib->fd) == false) {
 243     close(newlib->fd);
 244     free(newlib);
 245     return NULL;
 246   }
 247 #endif // __APPLE__
 248 
 249   newlib->symtab = build_symtab(newlib->fd);
 250   if (newlib->symtab == NULL) {
 251     print_debug("symbol table build failed for %s\n", newlib->name);
 252   } else {
 253     print_debug("built symbol table for %s\n", newlib->name);
 254   }
 255 
 256   // even if symbol table building fails, we add the lib_info.
 257   // This is because we may need to read from the ELF file or MachO file for core file
 258   // address read functionality. lookup_symbol checks for NULL symtab.
 259   if (ph->libs) {
 260     ph->lib_tail->next = newlib;
 261     ph->lib_tail = newlib;
 262   }  else {
 263     ph->libs = ph->lib_tail = newlib;
 264   }
 265   ph->num_libs++;
 266   return newlib;
 267 }
 268 
 269 // lookup for a specific symbol
 270 uintptr_t lookup_symbol(struct ps_prochandle* ph,  const char* object_name,
 271                        const char* sym_name) {
 272   // ignore object_name. search in all libraries
 273   // FIXME: what should we do with object_name?? The library names are obtained
 274   // by parsing /proc/<pid>/maps, which may not be the same as object_name.
 275   // What we need is a utility to map object_name to real file name, something
 276   // dlopen() does by looking at LD_LIBRARY_PATH and /etc/ld.so.cache. For
 277   // now, we just ignore object_name and do a global search for the symbol.
 278 
 279   lib_info* lib = ph->libs;
 280   while (lib) {
 281     if (lib->symtab) {
 282       uintptr_t res = search_symbol(lib->symtab, lib->base, sym_name, NULL);
 283       if (res) return res;
 284     }
 285     lib = lib->next;
 286   }
 287 
 288   print_debug("lookup failed for symbol '%s' in obj '%s'\n",
 289                           sym_name, object_name);
 290   return (uintptr_t) NULL;
 291 }
 292 
 293 const char* symbol_for_pc(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* poffset) {
 294   const char* res = NULL;
 295   lib_info* lib = ph->libs;
 296   while (lib) {
 297     if (lib->symtab && addr >= lib->base) {
 298       res = nearest_symbol(lib->symtab, addr - lib->base, poffset);
 299       if (res) return res;
 300     }
 301     lib = lib->next;
 302   }
 303   return NULL;
 304 }
 305 
 306 // add a thread to ps_prochandle
 307 sa_thread_info* add_thread_info(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id) {
 308   sa_thread_info* newthr;
 309   if ( (newthr = (sa_thread_info*) calloc(1, sizeof(sa_thread_info))) == NULL) {
 310     print_debug("can't allocate memory for thread_info\n");
 311     return NULL;
 312   }
 313 
 314   // initialize thread info
 315   newthr->pthread_id = pthread_id;
 316   newthr->lwp_id = lwp_id;
 317 
 318   // add new thread to the list
 319   newthr->next = ph->threads;
 320   ph->threads = newthr;
 321   ph->num_threads++;
 322   return newthr;
 323 }
 324 
 325 #ifndef __APPLE__
 326 // struct used for client data from thread_db callback
 327 struct thread_db_client_data {
 328   struct ps_prochandle* ph;
 329   thread_info_callback callback;
 330 };
 331 
 332 // callback function for libthread_db
 333 static int thread_db_callback(const td_thrhandle_t *th_p, void *data) {
 334   struct thread_db_client_data* ptr = (struct thread_db_client_data*) data;
 335   td_thrinfo_t ti;
 336   td_err_e err;
 337 
 338   memset(&ti, 0, sizeof(ti));
 339   err = td_thr_get_info(th_p, &ti);
 340   if (err != TD_OK) {
 341     print_debug("libthread_db : td_thr_get_info failed, can't get thread info\n");
 342     return err;
 343   }
 344 
 345   print_debug("thread_db : pthread %d (lwp %d)\n", ti.ti_tid, ti.ti_lid);
 346 
 347   if (ptr->callback(ptr->ph, (pthread_t)ti.ti_tid, ti.ti_lid) != true)
 348     return TD_ERR;
 349 
 350   return TD_OK;
 351 }
 352 
 353 // read thread_info using libthread_db
 354 bool read_thread_info(struct ps_prochandle* ph, thread_info_callback cb) {
 355   struct thread_db_client_data mydata;
 356   td_thragent_t* thread_agent = NULL;
 357   if (td_ta_new(ph, &thread_agent) != TD_OK) {
 358      print_debug("can't create libthread_db agent\n");
 359      return false;
 360   }
 361 
 362   mydata.ph = ph;
 363   mydata.callback = cb;
 364 
 365   // we use libthread_db iterator to iterate thru list of threads.
 366   if (td_ta_thr_iter(thread_agent, thread_db_callback, &mydata,
 367                  TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
 368                  TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS) != TD_OK) {
 369      td_ta_delete(thread_agent);
 370      return false;
 371   }
 372 
 373   // delete thread agent
 374   td_ta_delete(thread_agent);
 375   return true;
 376 }
 377 
 378 #endif // __APPLE__
 379 
 380 // get number of threads
 381 int get_num_threads(struct ps_prochandle* ph) {
 382    return ph->num_threads;
 383 }
 384 
 385 // get lwp_id of n'th thread
 386 lwpid_t get_lwp_id(struct ps_prochandle* ph, int index) {
 387   int count = 0;
 388   sa_thread_info* thr = ph->threads;
 389   while (thr) {
 390     if (count == index) {
 391       return thr->lwp_id;
 392     }
 393     count++;
 394     thr = thr->next;
 395   }
 396   return 0;
 397 }
 398 
 399 #ifdef __APPLE__
 400 // set lwp_id of n'th thread
 401 bool set_lwp_id(struct ps_prochandle* ph, int index, lwpid_t lwpid) {
 402   int count = 0;
 403   sa_thread_info* thr = ph->threads;
 404   while (thr) {
 405     if (count == index) {
 406       thr->lwp_id = lwpid;
 407       return true;
 408     }
 409     count++;
 410     thr = thr->next;
 411   }
 412   return false;
 413 }
 414 
 415 // get regs of n-th thread, only used in fillThreads the first time called
 416 bool get_nth_lwp_regs(struct ps_prochandle* ph, int index, struct reg* regs) {
 417   int count = 0;
 418   sa_thread_info* thr = ph->threads;
 419   while (thr) {
 420     if (count == index) {
 421       break;
 422     }
 423     count++;
 424     thr = thr->next;
 425   }
 426   if (thr != NULL) {
 427     memcpy(regs, &thr->regs, sizeof(struct reg));
 428     return true;
 429   }
 430   return false;
 431 }
 432 
 433 #endif // __APPLE__
 434 
 435 // get regs for a given lwp
 436 bool get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id, struct reg* regs) {
 437   return ph->ops->get_lwp_regs(ph, lwp_id, regs);
 438 }
 439 
 440 // get number of shared objects
 441 int get_num_libs(struct ps_prochandle* ph) {
 442   return ph->num_libs;
 443 }
 444 
 445 // get name of n'th solib
 446 const char* get_lib_name(struct ps_prochandle* ph, int index) {
 447   int count = 0;
 448   lib_info* lib = ph->libs;
 449   while (lib) {
 450     if (count == index) {
 451       return lib->name;
 452     }
 453     count++;
 454     lib = lib->next;
 455   }
 456   return NULL;
 457 }
 458 
 459 // get base address of a lib
 460 uintptr_t get_lib_base(struct ps_prochandle* ph, int index) {
 461   int count = 0;
 462   lib_info* lib = ph->libs;
 463   while (lib) {
 464     if (count == index) {
 465       return lib->base;
 466     }
 467     count++;
 468     lib = lib->next;
 469   }
 470   return (uintptr_t)NULL;
 471 }
 472 
 473 bool find_lib(struct ps_prochandle* ph, const char *lib_name) {
 474   lib_info *p = ph->libs;
 475   while (p) {
 476     if (strcmp(p->name, lib_name) == 0) {
 477       return true;
 478     }
 479     p = p->next;
 480   }
 481   return false;
 482 }
 483 
 484 //--------------------------------------------------------------------------
 485 // proc service functions
 486 
 487 // ps_pglobal_lookup() looks up the symbol sym_name in the symbol table
 488 // of the load object object_name in the target process identified by ph.
 489 // It returns the symbol's value as an address in the target process in
 490 // *sym_addr.
 491 
 492 ps_err_e ps_pglobal_lookup(struct ps_prochandle *ph, const char *object_name,
 493                     const char *sym_name, psaddr_t *sym_addr) {
 494   *sym_addr = (psaddr_t) lookup_symbol(ph, object_name, sym_name);
 495   return (*sym_addr ? PS_OK : PS_NOSYM);
 496 }
 497 
 498 // read "size" bytes info "buf" from address "addr"
 499 ps_err_e ps_pread(struct ps_prochandle *ph, psaddr_t  addr,
 500                   void *buf, size_t size) {
 501   return ph->ops->p_pread(ph, (uintptr_t) addr, buf, size)? PS_OK: PS_ERR;
 502 }
 503 
 504 // write "size" bytes of data to debuggee at address "addr"
 505 ps_err_e ps_pwrite(struct ps_prochandle *ph, psaddr_t addr,
 506                    const void *buf, size_t size) {
 507   return ph->ops->p_pwrite(ph, (uintptr_t)addr, buf, size)? PS_OK: PS_ERR;
 508 }
 509 
 510 // fill in ptrace_lwpinfo for lid
 511 ps_err_e ps_linfo(struct ps_prochandle *ph, lwpid_t lwp_id, void *linfo) {
 512   return ph->ops->get_lwp_info(ph, lwp_id, linfo)? PS_OK: PS_ERR;
 513 }
 514 
 515 // needed for when libthread_db is compiled with TD_DEBUG defined
 516 void
 517 ps_plog (const char *format, ...)
 518 {
 519   va_list alist;
 520 
 521   va_start(alist, format);
 522   vfprintf(stderr, format, alist);
 523   va_end(alist);
 524 }
 525 
 526 #ifndef __APPLE__
 527 // ------------------------------------------------------------------------
 528 // Functions below this point are not yet implemented. They are here only
 529 // to make the linker happy.
 530 
 531 ps_err_e ps_lsetfpregs(struct ps_prochandle *ph, lwpid_t lid, const prfpregset_t *fpregs) {
 532   print_debug("ps_lsetfpregs not implemented\n");
 533   return PS_OK;
 534 }
 535 
 536 ps_err_e ps_lsetregs(struct ps_prochandle *ph, lwpid_t lid, const prgregset_t gregset) {
 537   print_debug("ps_lsetregs not implemented\n");
 538   return PS_OK;
 539 }
 540 
 541 ps_err_e  ps_lgetfpregs(struct  ps_prochandle  *ph,  lwpid_t lid, prfpregset_t *fpregs) {
 542   print_debug("ps_lgetfpregs not implemented\n");
 543   return PS_OK;
 544 }
 545 
 546 ps_err_e ps_lgetregs(struct ps_prochandle *ph, lwpid_t lid, prgregset_t gregset) {
 547   print_debug("ps_lgetfpregs not implemented\n");
 548   return PS_OK;
 549 }
 550 
 551 ps_err_e ps_lstop(struct ps_prochandle *ph, lwpid_t lid) {
 552   print_debug("ps_lstop not implemented\n");
 553   return PS_OK;
 554 }
 555 
 556 ps_err_e ps_pcontinue(struct ps_prochandle *ph) {
 557   print_debug("ps_pcontinue not implemented\n");
 558   return PS_OK;
 559 }
 560 #endif // __APPLE__