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