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 
 278 // struct used for client data from thread_db callback
 279 struct thread_db_client_data {
 280    struct ps_prochandle* ph;
 281    thread_info_callback callback;
 282 };
 283 
 284 // callback function for libthread_db
 285 static int thread_db_callback(const td_thrhandle_t *th_p, void *data) {
 286   struct thread_db_client_data* ptr = (struct thread_db_client_data*) data;
 287   td_thrinfo_t ti;
 288   td_err_e err;
 289 
 290   memset(&ti, 0, sizeof(ti));
 291   err = td_thr_get_info(th_p, &ti);
 292   if (err != TD_OK) {
 293     print_debug("libthread_db : td_thr_get_info failed, can't get thread info\n");
 294     return err;
 295   }
 296 
 297   print_debug("thread_db : pthread %d (lwp %d)\n", ti.ti_tid, ti.ti_lid);
 298 
 299   if (ptr->callback(ptr->ph, ti.ti_tid, ti.ti_lid) != true)
 300     return TD_ERR;
 301 
 302   return TD_OK;
 303 }
 304 
 305 // read thread_info using libthread_db
 306 bool read_thread_info(struct ps_prochandle* ph, thread_info_callback cb) {
 307   struct thread_db_client_data mydata;
 308   td_thragent_t* thread_agent = NULL;
 309   if (td_ta_new(ph, &thread_agent) != TD_OK) {
 310      print_debug("can't create libthread_db agent\n");
 311      return false;
 312   }
 313 
 314   mydata.ph = ph;
 315   mydata.callback = cb;
 316 
 317   // we use libthread_db iterator to iterate thru list of threads.
 318   if (td_ta_thr_iter(thread_agent, thread_db_callback, &mydata,
 319                  TD_THR_ANY_STATE, TD_THR_LOWEST_PRIORITY,
 320                  TD_SIGNO_MASK, TD_THR_ANY_USER_FLAGS) != TD_OK) {
 321      td_ta_delete(thread_agent);
 322      return false;
 323   }
 324 
 325   // delete thread agent
 326   td_ta_delete(thread_agent);
 327   return true;
 328 }
 329 
 330 
 331 // get number of threads
 332 int get_num_threads(struct ps_prochandle* ph) {
 333    return ph->num_threads;
 334 }
 335 
 336 // get lwp_id of n'th thread
 337 lwpid_t get_lwp_id(struct ps_prochandle* ph, int index) {
 338    int count = 0;
 339    thread_info* thr = ph->threads;
 340    while (thr) {
 341       if (count == index) {
 342          return thr->lwp_id;
 343       }
 344       count++;
 345       thr = thr->next;
 346    }
 347    return -1;
 348 }
 349 
 350 // get regs for a given lwp
 351 bool get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id, struct user_regs_struct* regs) {
 352   return ph->ops->get_lwp_regs(ph, lwp_id, regs);
 353 }
 354 
 355 // get number of shared objects
 356 int get_num_libs(struct ps_prochandle* ph) {
 357    return ph->num_libs;
 358 }
 359 
 360 // get name of n'th solib
 361 const char* get_lib_name(struct ps_prochandle* ph, int index) {
 362    int count = 0;
 363    lib_info* lib = ph->libs;
 364    while (lib) {
 365       if (count == index) {
 366          return lib->name;
 367       }
 368       count++;
 369       lib = lib->next;
 370    }
 371    return NULL;
 372 }
 373 
 374 // get base address of a lib
 375 uintptr_t get_lib_base(struct ps_prochandle* ph, int index) {
 376    int count = 0;
 377    lib_info* lib = ph->libs;
 378    while (lib) {
 379       if (count == index) {
 380          return lib->base;
 381       }
 382       count++;
 383       lib = lib->next;
 384    }
 385    return (uintptr_t)NULL;
 386 }
 387 
 388 bool find_lib(struct ps_prochandle* ph, const char *lib_name) {
 389   lib_info *p = ph->libs;
 390   while (p) {
 391     if (strcmp(p->name, lib_name) == 0) {
 392       return true;
 393     }
 394     p = p->next;
 395   }
 396   return false;
 397 }
 398 
 399 //--------------------------------------------------------------------------
 400 // proc service functions
 401 
 402 // get process id
 403 JNIEXPORT pid_t JNICALL
 404 ps_getpid(struct ps_prochandle *ph) {
 405    return ph->pid;
 406 }
 407 
 408 // ps_pglobal_lookup() looks up the symbol sym_name in the symbol table
 409 // of the load object object_name in the target process identified by ph.
 410 // It returns the symbol's value as an address in the target process in
 411 // *sym_addr.
 412 
 413 JNIEXPORT ps_err_e JNICALL
 414 ps_pglobal_lookup(struct ps_prochandle *ph, const char *object_name,
 415                     const char *sym_name, psaddr_t *sym_addr) {
 416   *sym_addr = (psaddr_t) lookup_symbol(ph, object_name, sym_name);
 417   return (*sym_addr ? PS_OK : PS_NOSYM);
 418 }
 419 
 420 // read "size" bytes info "buf" from address "addr"
 421 JNIEXPORT ps_err_e JNICALL
 422 ps_pdread(struct ps_prochandle *ph, psaddr_t  addr,
 423                    void *buf, size_t size) {
 424   return ph->ops->p_pread(ph, (uintptr_t) addr, buf, size)? PS_OK: PS_ERR;
 425 }
 426 
 427 // write "size" bytes of data to debuggee at address "addr"
 428 JNIEXPORT ps_err_e JNICALL
 429 ps_pdwrite(struct ps_prochandle *ph, psaddr_t addr,
 430                     const void *buf, size_t size) {
 431   return ph->ops->p_pwrite(ph, (uintptr_t)addr, buf, size)? PS_OK: PS_ERR;
 432 }
 433 
 434 // ------------------------------------------------------------------------
 435 // Functions below this point are not yet implemented. They are here only
 436 // to make the linker happy.
 437 
 438 JNIEXPORT ps_err_e JNICALL
 439 ps_lsetfpregs(struct ps_prochandle *ph, lwpid_t lid, const prfpregset_t *fpregs) {
 440   print_debug("ps_lsetfpregs not implemented\n");
 441   return PS_OK;
 442 }
 443 
 444 JNIEXPORT ps_err_e JNICALL
 445 ps_lsetregs(struct ps_prochandle *ph, lwpid_t lid, const prgregset_t gregset) {
 446   print_debug("ps_lsetregs not implemented\n");
 447   return PS_OK;
 448 }
 449 
 450 JNIEXPORT ps_err_e  JNICALL
 451 ps_lgetfpregs(struct  ps_prochandle  *ph,  lwpid_t lid, prfpregset_t *fpregs) {
 452   print_debug("ps_lgetfpregs not implemented\n");
 453   return PS_OK;
 454 }
 455 
 456 JNIEXPORT ps_err_e JNICALL
 457 ps_lgetregs(struct ps_prochandle *ph, lwpid_t lid, prgregset_t gregset) {
 458   print_debug("ps_lgetfpregs not implemented\n");
 459   return PS_OK;
 460 }
 461 
 462 // new libthread_db of NPTL seem to require this symbol
 463 JNIEXPORT ps_err_e JNICALL
 464 ps_get_thread_area() {
 465   print_debug("ps_get_thread_area not implemented\n");
 466   return PS_OK;
 467 }