1 /*
   2  * Copyright (c) 2003, 2018, 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 <stdarg.h>
  25 #include <stdio.h>
  26 #include <stdlib.h>
  27 #include <string.h>
  28 #include <fcntl.h>
  29 #include <thread_db.h>
  30 #include "libproc_impl.h"
  31 
  32 #define SA_ALTROOT "SA_ALTROOT"
  33 
  34 int pathmap_open(const char* name) {
  35   static const char *alt_root = NULL;
  36   static int alt_root_initialized = 0;
  37 
  38   int fd;
  39   char alt_path[PATH_MAX + 1], *alt_path_end;
  40   const char *s;
  41   int free_space;
  42 
  43   if (!alt_root_initialized) {
  44     alt_root_initialized = -1;
  45     alt_root = getenv(SA_ALTROOT);
  46   }
  47 
  48   if (alt_root == NULL) {
  49     return open(name, O_RDONLY);
  50   }
  51 
  52 
  53   if (strlen(alt_root) + strlen(name) > PATH_MAX) {
  54     // Buffer too small.
  55     return -1;
  56   }
  57 
  58   strncpy(alt_path, alt_root, PATH_MAX);
  59   alt_path[PATH_MAX] = '\0';
  60   alt_path_end = alt_path + strlen(alt_path);
  61   free_space = PATH_MAX + 1 - (alt_path_end-alt_path);
  62 
  63   // Strip path items one by one and try to open file with alt_root prepended.
  64   s = name;
  65   while (1) {
  66     strncat(alt_path, s, free_space);
  67     s += 1;  // Skip /.
  68 
  69     fd = open(alt_path, O_RDONLY);
  70     if (fd >= 0) {
  71       print_debug("path %s substituted for %s\n", alt_path, name);
  72       return fd;
  73     }
  74 
  75     // Linker always put full path to solib to process, so we can rely
  76     // on presence of /. If slash is not present, it means, that SOlib doesn't
  77     // physically exist (e.g. linux-gate.so) and we fail opening it anyway
  78     if ((s = strchr(s, '/')) == NULL) {
  79       break;
  80     }
  81 
  82     // Cut off what we appended above.
  83     *alt_path_end = '\0';
  84   }
  85 
  86   return -1;
  87 }
  88 
  89 static bool _libsaproc_debug;
  90 
  91 void print_debug(const char* format,...) {
  92    if (_libsaproc_debug) {
  93      va_list alist;
  94 
  95      va_start(alist, format);
  96      fputs("libsaproc DEBUG: ", stderr);
  97      vfprintf(stderr, format, alist);
  98      va_end(alist);
  99    }
 100 }
 101 
 102 void print_error(const char* format,...) {
 103   va_list alist;
 104   va_start(alist, format);
 105   fputs("ERROR: ", stderr);
 106   vfprintf(stderr, format, alist);
 107   va_end(alist);
 108 }
 109 
 110 bool is_debug() {
 111    return _libsaproc_debug;
 112 }
 113 
 114 // initialize libproc
 115 JNIEXPORT bool JNICALL
 116 init_libproc(bool debug) {
 117    // init debug mode
 118    _libsaproc_debug = debug;
 119 
 120    // initialize the thread_db library
 121    if (td_init() != TD_OK) {
 122      print_debug("libthread_db's td_init failed\n");
 123      return false;
 124    }
 125 
 126    return true;
 127 }
 128 
 129 static void destroy_lib_info(struct ps_prochandle* ph) {
 130    lib_info* lib = ph->libs;
 131    while (lib) {
 132      lib_info *next = lib->next;
 133      if (lib->symtab) {
 134         destroy_symtab(lib->symtab);
 135      }
 136      free(lib);
 137      lib = next;
 138    }
 139 }
 140 
 141 static void destroy_thread_info(struct ps_prochandle* ph) {
 142    thread_info* thr = ph->threads;
 143    while (thr) {
 144      thread_info *next = thr->next;
 145      free(thr);
 146      thr = next;
 147    }
 148 }
 149 
 150 // ps_prochandle cleanup
 151 
 152 // ps_prochandle cleanup
 153 JNIEXPORT void JNICALL
 154 Prelease(struct ps_prochandle* ph) {
 155    // do the "derived class" clean-up first
 156    ph->ops->release(ph);
 157    destroy_lib_info(ph);
 158    destroy_thread_info(ph);
 159    free(ph);
 160 }
 161 
 162 lib_info* add_lib_info(struct ps_prochandle* ph, const char* libname, uintptr_t base) {
 163    return add_lib_info_fd(ph, libname, -1, base);
 164 }
 165 
 166 lib_info* add_lib_info_fd(struct ps_prochandle* ph, const char* libname, int fd, uintptr_t base) {
 167    lib_info* newlib;
 168 
 169    if ( (newlib = (lib_info*) calloc(1, sizeof(struct lib_info))) == NULL) {
 170       print_debug("can't allocate memory for lib_info\n");
 171       return NULL;
 172    }
 173 
 174    if (strlen(libname) >= sizeof(newlib->name)) {
 175      print_debug("libname %s too long\n", libname);
 176      free(newlib);
 177      return NULL;
 178    }
 179    strcpy(newlib->name, libname);
 180 
 181    newlib->base = base;
 182 
 183    if (fd == -1) {
 184       if ( (newlib->fd = pathmap_open(newlib->name)) < 0) {
 185          print_debug("can't open shared object %s\n", newlib->name);
 186          free(newlib);
 187          return NULL;
 188       }
 189    } else {
 190       newlib->fd = fd;
 191    }
 192 
 193    // check whether we have got an ELF file. /proc/<pid>/map
 194    // gives out all file mappings and not just shared objects
 195    if (is_elf_file(newlib->fd) == false) {
 196       close(newlib->fd);
 197       free(newlib);
 198       return NULL;
 199    }
 200 
 201    newlib->symtab = build_symtab(newlib->fd, libname);
 202    if (newlib->symtab == NULL) {
 203       print_debug("symbol table build failed for %s\n", newlib->name);
 204    }
 205 
 206    // even if symbol table building fails, we add the lib_info.
 207    // This is because we may need to read from the ELF file for core file
 208    // address read functionality. lookup_symbol checks for NULL symtab.
 209    if (ph->libs) {
 210       ph->lib_tail->next = newlib;
 211       ph->lib_tail = newlib;
 212    }  else {
 213       ph->libs = ph->lib_tail = newlib;
 214    }
 215    ph->num_libs++;
 216 
 217    return newlib;
 218 }
 219 
 220 // lookup for a specific symbol
 221 uintptr_t lookup_symbol(struct ps_prochandle* ph,  const char* object_name,
 222                        const char* sym_name) {
 223    // ignore object_name. search in all libraries
 224    // FIXME: what should we do with object_name?? The library names are obtained
 225    // by parsing /proc/<pid>/maps, which may not be the same as object_name.
 226    // What we need is a utility to map object_name to real file name, something
 227    // dlopen() does by looking at LD_LIBRARY_PATH and /etc/ld.so.cache. For
 228    // now, we just ignore object_name and do a global search for the symbol.
 229 
 230    lib_info* lib = ph->libs;
 231    while (lib) {
 232       if (lib->symtab) {
 233          uintptr_t res = search_symbol(lib->symtab, lib->base, sym_name, NULL);
 234          if (res) return res;
 235       }
 236       lib = lib->next;
 237    }
 238 
 239    print_debug("lookup failed for symbol '%s' in obj '%s'\n",
 240                           sym_name, object_name);
 241    return (uintptr_t) NULL;
 242 }
 243 
 244 
 245 const char* symbol_for_pc(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* poffset) {
 246    const char* res = NULL;
 247    lib_info* lib = ph->libs;
 248    while (lib) {
 249       if (lib->symtab && addr >= lib->base) {
 250          res = nearest_symbol(lib->symtab, addr - lib->base, poffset);
 251          if (res) return res;
 252       }
 253       lib = lib->next;
 254    }
 255    return NULL;
 256 }
 257 
 258 // add a thread to ps_prochandle
 259 thread_info* add_thread_info(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id) {
 260    thread_info* newthr;
 261    if ( (newthr = (thread_info*) calloc(1, sizeof(thread_info))) == NULL) {
 262       print_debug("can't allocate memory for thread_info\n");
 263       return NULL;
 264    }
 265 
 266    // initialize thread info
 267    newthr->pthread_id = pthread_id;
 268    newthr->lwp_id = lwp_id;
 269 
 270    // add new thread to the list
 271    newthr->next = ph->threads;
 272    ph->threads = newthr;
 273    ph->num_threads++;
 274    return newthr;
 275 }
 276 
 277 void delete_thread_info(struct ps_prochandle* ph, thread_info* thr_to_be_removed) {
 278     thread_info* current_thr = ph->threads;
 279 
 280     if (thr_to_be_removed == ph->threads) {
 281       ph->threads = ph->threads->next;
 282     } else {
 283       thread_info* previous_thr;
 284       while (current_thr && current_thr != thr_to_be_removed) {
 285         previous_thr = current_thr;
 286         current_thr = current_thr->next;
 287       }
 288       if (current_thr == NULL) {
 289         print_error("Could not find the thread to be removed");
 290         return;
 291       }
 292       previous_thr->next = current_thr->next;
 293     }
 294     ph->num_threads--;
 295     free(current_thr);
 296 }
 297 
 298 // struct used for client data from thread_db callback
 299 struct thread_db_client_data {
 300    struct ps_prochandle* ph;
 301    thread_info_callback callback;
 302 };
 303 
 304 // callback function for libthread_db
 305 static int thread_db_callback(const td_thrhandle_t *th_p, void *data) {
 306   struct thread_db_client_data* ptr = (struct thread_db_client_data*) data;
 307   td_thrinfo_t ti;
 308   td_err_e err;
 309 
 310   memset(&ti, 0, sizeof(ti));
 311   err = td_thr_get_info(th_p, &ti);
 312   if (err != TD_OK) {
 313     print_debug("libthread_db : td_thr_get_info failed, can't get thread info\n");
 314     return err;
 315   }
 316 
 317   print_debug("thread_db : pthread %d (lwp %d)\n", ti.ti_tid, ti.ti_lid);
 318 
 319   if (ti.ti_state == TD_THR_UNKNOWN || ti.ti_state == TD_THR_ZOMBIE) {
 320     print_debug("Skipping pthread %d (lwp %d)\n", ti.ti_tid, ti.ti_lid);
 321     return TD_OK;
 322   }
 323 
 324   if (ptr->callback(ptr->ph, ti.ti_tid, ti.ti_lid) != true)
 325     return TD_ERR;
 326 
 327   return TD_OK;
 328 }
 329 
 330 // read thread_info using libthread_db
 331 bool read_thread_info(struct ps_prochandle* ph, thread_info_callback cb) {
 332   struct thread_db_client_data mydata;
 333   td_thragent_t* thread_agent = NULL;
 334   if (td_ta_new(ph, &thread_agent) != TD_OK) {
 335      print_debug("can't create libthread_db agent\n");
 336      return false;
 337   }
 338 
 339   mydata.ph = ph;
 340   mydata.callback = cb;
 341 
 342   // we use libthread_db iterator to iterate thru list of threads.
 343   if (td_ta_thr_iter(thread_agent, thread_db_callback, &mydata,
 344                  TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
 345                  TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS) != TD_OK) {
 346      td_ta_delete(thread_agent);
 347      return false;
 348   }
 349 
 350   // delete thread agent
 351   td_ta_delete(thread_agent);
 352   return true;
 353 }
 354 
 355 
 356 // get number of threads
 357 int get_num_threads(struct ps_prochandle* ph) {
 358    return ph->num_threads;
 359 }
 360 
 361 // get lwp_id of n'th thread
 362 lwpid_t get_lwp_id(struct ps_prochandle* ph, int index) {
 363    int count = 0;
 364    thread_info* thr = ph->threads;
 365    while (thr) {
 366       if (count == index) {
 367          return thr->lwp_id;
 368       }
 369       count++;
 370       thr = thr->next;
 371    }
 372    return -1;
 373 }
 374 
 375 // get regs for a given lwp
 376 bool get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id, struct user_regs_struct* regs) {
 377   return ph->ops->get_lwp_regs(ph, lwp_id, regs);
 378 }
 379 
 380 // get number of shared objects
 381 int get_num_libs(struct ps_prochandle* ph) {
 382    return ph->num_libs;
 383 }
 384 
 385 // get name of n'th solib
 386 const char* get_lib_name(struct ps_prochandle* ph, int index) {
 387    int count = 0;
 388    lib_info* lib = ph->libs;
 389    while (lib) {
 390       if (count == index) {
 391          return lib->name;
 392       }
 393       count++;
 394       lib = lib->next;
 395    }
 396    return NULL;
 397 }
 398 
 399 // get base address of a lib
 400 uintptr_t get_lib_base(struct ps_prochandle* ph, int index) {
 401    int count = 0;
 402    lib_info* lib = ph->libs;
 403    while (lib) {
 404       if (count == index) {
 405          return lib->base;
 406       }
 407       count++;
 408       lib = lib->next;
 409    }
 410    return (uintptr_t)NULL;
 411 }
 412 
 413 bool find_lib(struct ps_prochandle* ph, const char *lib_name) {
 414   lib_info *p = ph->libs;
 415   while (p) {
 416     if (strcmp(p->name, lib_name) == 0) {
 417       return true;
 418     }
 419     p = p->next;
 420   }
 421   return false;
 422 }
 423 
 424 //--------------------------------------------------------------------------
 425 // proc service functions
 426 
 427 // get process id
 428 JNIEXPORT pid_t JNICALL
 429 ps_getpid(struct ps_prochandle *ph) {
 430    return ph->pid;
 431 }
 432 
 433 // ps_pglobal_lookup() looks up the symbol sym_name in the symbol table
 434 // of the load object object_name in the target process identified by ph.
 435 // It returns the symbol's value as an address in the target process in
 436 // *sym_addr.
 437 
 438 JNIEXPORT ps_err_e JNICALL
 439 ps_pglobal_lookup(struct ps_prochandle *ph, const char *object_name,
 440                     const char *sym_name, psaddr_t *sym_addr) {
 441   *sym_addr = (psaddr_t) lookup_symbol(ph, object_name, sym_name);
 442   return (*sym_addr ? PS_OK : PS_NOSYM);
 443 }
 444 
 445 // read "size" bytes info "buf" from address "addr"
 446 JNIEXPORT ps_err_e JNICALL
 447 ps_pdread(struct ps_prochandle *ph, psaddr_t  addr,
 448                    void *buf, size_t size) {
 449   return ph->ops->p_pread(ph, (uintptr_t) addr, buf, size)? PS_OK: PS_ERR;
 450 }
 451 
 452 // write "size" bytes of data to debuggee at address "addr"
 453 JNIEXPORT ps_err_e JNICALL
 454 ps_pdwrite(struct ps_prochandle *ph, psaddr_t addr,
 455                     const void *buf, size_t size) {
 456   return ph->ops->p_pwrite(ph, (uintptr_t)addr, buf, size)? PS_OK: PS_ERR;
 457 }
 458 
 459 // ------------------------------------------------------------------------
 460 // Functions below this point are not yet implemented. They are here only
 461 // to make the linker happy.
 462 
 463 JNIEXPORT ps_err_e JNICALL
 464 ps_lsetfpregs(struct ps_prochandle *ph, lwpid_t lid, const prfpregset_t *fpregs) {
 465   print_debug("ps_lsetfpregs not implemented\n");
 466   return PS_OK;
 467 }
 468 
 469 JNIEXPORT ps_err_e JNICALL
 470 ps_lsetregs(struct ps_prochandle *ph, lwpid_t lid, const prgregset_t gregset) {
 471   print_debug("ps_lsetregs not implemented\n");
 472   return PS_OK;
 473 }
 474 
 475 JNIEXPORT ps_err_e  JNICALL
 476 ps_lgetfpregs(struct  ps_prochandle  *ph,  lwpid_t lid, prfpregset_t *fpregs) {
 477   print_debug("ps_lgetfpregs not implemented\n");
 478   return PS_OK;
 479 }
 480 
 481 JNIEXPORT ps_err_e JNICALL
 482 ps_lgetregs(struct ps_prochandle *ph, lwpid_t lid, prgregset_t gregset) {
 483   print_debug("ps_lgetfpregs not implemented\n");
 484   return PS_OK;
 485 }
 486 
 487 // new libthread_db of NPTL seem to require this symbol
 488 JNIEXPORT ps_err_e JNICALL
 489 ps_get_thread_area() {
 490   print_debug("ps_get_thread_area not implemented\n");
 491   return PS_OK;
 492 }