1 /*
   2  * Copyright (c) 2003, 2020, 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 <sys/procfs.h>
  30 #include "libproc_impl.h"
  31 #include "proc_service.h"
  32 #include "salibelf.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 JNIEXPORT bool JNICALL
 118 init_libproc(bool debug) {
 119    // init debug mode
 120    _libsaproc_debug = debug;
 121    return true;
 122 }
 123 
 124 static void destroy_lib_info(struct ps_prochandle* ph) {
 125    lib_info* lib = ph->libs;
 126    while (lib) {
 127      lib_info *next = lib->next;
 128      if (lib->symtab) {
 129         destroy_symtab(lib->symtab);
 130      }
 131      free(lib->eh_frame.data);
 132      free(lib);
 133      lib = next;
 134    }
 135 }
 136 
 137 static void destroy_thread_info(struct ps_prochandle* ph) {
 138    thread_info* thr = ph->threads;
 139    while (thr) {
 140      thread_info *next = thr->next;
 141      free(thr);
 142      thr = next;
 143    }
 144 }
 145 
 146 // ps_prochandle cleanup
 147 
 148 // ps_prochandle cleanup
 149 JNIEXPORT void JNICALL
 150 Prelease(struct ps_prochandle* ph) {
 151    // do the "derived class" clean-up first
 152    ph->ops->release(ph);
 153    destroy_lib_info(ph);
 154    destroy_thread_info(ph);
 155    free(ph);
 156 }
 157 
 158 lib_info* add_lib_info(struct ps_prochandle* ph, const char* libname, uintptr_t base) {
 159    return add_lib_info_fd(ph, libname, -1, base);
 160 }
 161 
 162 static bool fill_instr_info(lib_info* lib) {
 163   off_t current_pos;
 164   ELF_EHDR ehdr;
 165   ELF_PHDR* phbuf = NULL;
 166   ELF_PHDR* ph = NULL;
 167   int cnt;
 168   long align = sysconf(_SC_PAGE_SIZE);
 169 
 170   current_pos = lseek(lib->fd, (off_t)0L, SEEK_CUR);
 171   lseek(lib->fd, (off_t)0L, SEEK_SET);
 172   read_elf_header(lib->fd, &ehdr);
 173   if ((phbuf = read_program_header_table(lib->fd, &ehdr)) == NULL) {
 174     lseek(lib->fd, current_pos, SEEK_SET);
 175     return false;
 176   }
 177 
 178   lib->exec_start = 0L;
 179   lib->exec_end = 0L;
 180   for (ph = phbuf, cnt = 0; cnt < ehdr.e_phnum; cnt++, ph++) {
 181     if ((ph->p_type == PT_LOAD) && (ph->p_flags & PF_X)) {
 182       print_debug("[%d] vaddr = 0x%lx, memsz = 0x%lx, filesz = 0x%lx\n", cnt, ph->p_vaddr, ph->p_memsz, ph->p_filesz);
 183       if ((lib->exec_start == 0L) || (lib->exec_start > ph->p_vaddr)) {
 184         lib->exec_start = ph->p_vaddr;
 185       }
 186       if (lib->exec_end < (ph->p_vaddr + ph->p_memsz)) {
 187         lib->exec_end = ph->p_vaddr + ph->p_memsz;
 188       }
 189       align = ph->p_align;
 190     }
 191   }
 192 
 193   free(phbuf);
 194   lseek(lib->fd, current_pos, SEEK_SET);
 195 
 196   if ((lib->exec_start == 0L) || (lib->exec_end == 0L)) {
 197     return false;
 198   } else {
 199     lib->exec_start = (lib->exec_start + lib->base) & ~(align - 1);
 200     lib->exec_end = (lib->exec_end + lib->base + align) & ~(align - 1);
 201     return true;
 202   }
 203 
 204 }
 205 
 206 bool read_eh_frame(struct ps_prochandle* ph, lib_info* lib) {
 207   off_t current_pos = -1;
 208   ELF_EHDR ehdr;
 209   ELF_SHDR* shbuf = NULL;
 210   ELF_SHDR* sh = NULL;
 211   char* strtab = NULL;
 212   void* result = NULL;
 213   int cnt;
 214 
 215   current_pos = lseek(lib->fd, (off_t)0L, SEEK_CUR);
 216   lseek(lib->fd, (off_t)0L, SEEK_SET);
 217 
 218   read_elf_header(lib->fd, &ehdr);
 219   shbuf = read_section_header_table(lib->fd, &ehdr);
 220   strtab = read_section_data(lib->fd, &ehdr, &shbuf[ehdr.e_shstrndx]);
 221 
 222   for (cnt = 0, sh = shbuf; cnt < ehdr.e_shnum; cnt++, sh++) {
 223     if (strcmp(".eh_frame", sh->sh_name + strtab) == 0) {
 224       lib->eh_frame.library_base_addr = lib->base;
 225       lib->eh_frame.v_addr = sh->sh_addr;
 226       lib->eh_frame.data = read_section_data(lib->fd, &ehdr, sh);
 227       break;
 228     }
 229   }
 230 
 231   free(strtab);
 232   free(shbuf);
 233   lseek(lib->fd, current_pos, SEEK_SET);
 234   return lib->eh_frame.data != NULL;
 235 }
 236 
 237 lib_info* add_lib_info_fd(struct ps_prochandle* ph, const char* libname, int fd, uintptr_t base) {
 238    lib_info* newlib;
 239 
 240    if ( (newlib = (lib_info*) calloc(1, sizeof(struct lib_info))) == NULL) {
 241       print_debug("can't allocate memory for lib_info\n");
 242       return NULL;
 243    }
 244 
 245    if (strlen(libname) >= sizeof(newlib->name)) {
 246      print_debug("libname %s too long\n", libname);
 247      free(newlib);
 248      return NULL;
 249    }
 250    strcpy(newlib->name, libname);
 251 
 252    newlib->base = base;
 253 
 254    if (fd == -1) {
 255       if ( (newlib->fd = pathmap_open(newlib->name)) < 0) {
 256          print_debug("can't open shared object %s\n", newlib->name);
 257          free(newlib);
 258          return NULL;
 259       }
 260    } else {
 261       newlib->fd = fd;
 262    }
 263 
 264    // check whether we have got an ELF file. /proc/<pid>/map
 265    // gives out all file mappings and not just shared objects
 266    if (is_elf_file(newlib->fd) == false) {
 267       close(newlib->fd);
 268       free(newlib);
 269       return NULL;
 270    }
 271 
 272    newlib->symtab = build_symtab(newlib->fd, libname);
 273    if (newlib->symtab == NULL) {
 274       print_debug("symbol table build failed for %s\n", newlib->name);
 275    }
 276 
 277    if (fill_instr_info(newlib)) {
 278      if (!read_eh_frame(ph, newlib)) {
 279        print_debug("Could not find .eh_frame section in %s\n", newlib->name);
 280      }
 281    } else {
 282       print_debug("Could not find executable section in %s\n", newlib->name);
 283    }
 284 
 285    // even if symbol table building fails, we add the lib_info.
 286    // This is because we may need to read from the ELF file for core file
 287    // address read functionality. lookup_symbol checks for NULL symtab.
 288    if (ph->libs) {
 289       ph->lib_tail->next = newlib;
 290       ph->lib_tail = newlib;
 291    }  else {
 292       ph->libs = ph->lib_tail = newlib;
 293    }
 294    ph->num_libs++;
 295 
 296    return newlib;
 297 }
 298 
 299 // lookup for a specific symbol
 300 uintptr_t lookup_symbol(struct ps_prochandle* ph,  const char* object_name,
 301                        const char* sym_name) {
 302    // ignore object_name. search in all libraries
 303    // FIXME: what should we do with object_name?? The library names are obtained
 304    // by parsing /proc/<pid>/maps, which may not be the same as object_name.
 305    // What we need is a utility to map object_name to real file name, something
 306    // dlopen() does by looking at LD_LIBRARY_PATH and /etc/ld.so.cache. For
 307    // now, we just ignore object_name and do a global search for the symbol.
 308 
 309    lib_info* lib = ph->libs;
 310    while (lib) {
 311       if (lib->symtab) {
 312          uintptr_t res = search_symbol(lib->symtab, lib->base, sym_name, NULL);
 313          if (res) return res;
 314       }
 315       lib = lib->next;
 316    }
 317 
 318    print_debug("lookup failed for symbol '%s' in obj '%s'\n",
 319                           sym_name, object_name);
 320    return (uintptr_t) NULL;
 321 }
 322 
 323 
 324 const char* symbol_for_pc(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* poffset) {
 325    const char* res = NULL;
 326    lib_info* lib = ph->libs;
 327    while (lib) {
 328       if (lib->symtab && addr >= lib->base) {
 329          res = nearest_symbol(lib->symtab, addr - lib->base, poffset);
 330          if (res) return res;
 331       }
 332       lib = lib->next;
 333    }
 334    return NULL;
 335 }
 336 
 337 // add a thread to ps_prochandle
 338 thread_info* add_thread_info(struct ps_prochandle* ph, lwpid_t lwp_id) {
 339    thread_info* newthr;
 340    if ( (newthr = (thread_info*) calloc(1, sizeof(thread_info))) == NULL) {
 341       print_debug("can't allocate memory for thread_info\n");
 342       return NULL;
 343    }
 344 
 345    // initialize thread info
 346    newthr->lwp_id = lwp_id;
 347 
 348    // add new thread to the list
 349    newthr->next = ph->threads;
 350    ph->threads = newthr;
 351    ph->num_threads++;
 352    return newthr;
 353 }
 354 
 355 void delete_thread_info(struct ps_prochandle* ph, thread_info* thr_to_be_removed) {
 356     thread_info* current_thr = ph->threads;
 357 
 358     if (thr_to_be_removed == ph->threads) {
 359       ph->threads = ph->threads->next;
 360     } else {
 361       thread_info* previous_thr = NULL;
 362       while (current_thr && current_thr != thr_to_be_removed) {
 363         previous_thr = current_thr;
 364         current_thr = current_thr->next;
 365       }
 366       if (current_thr == NULL) {
 367         print_error("Could not find the thread to be removed");
 368         return;
 369       }
 370       previous_thr->next = current_thr->next;
 371     }
 372     ph->num_threads--;
 373     free(current_thr);
 374 }
 375 
 376 // get number of threads
 377 int get_num_threads(struct ps_prochandle* ph) {
 378    return ph->num_threads;
 379 }
 380 
 381 // get lwp_id of n'th thread
 382 lwpid_t get_lwp_id(struct ps_prochandle* ph, int index) {
 383    int count = 0;
 384    thread_info* thr = ph->threads;
 385    while (thr) {
 386       if (count == index) {
 387          return thr->lwp_id;
 388       }
 389       count++;
 390       thr = thr->next;
 391    }
 392    return -1;
 393 }
 394 
 395 // get regs for a given lwp
 396 bool get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id, struct user_regs_struct* regs) {
 397   return ph->ops->get_lwp_regs(ph, lwp_id, regs);
 398 }
 399 
 400 // get number of shared objects
 401 int get_num_libs(struct ps_prochandle* ph) {
 402    return ph->num_libs;
 403 }
 404 
 405 // get name of n'th solib
 406 const char* get_lib_name(struct ps_prochandle* ph, int index) {
 407    int count = 0;
 408    lib_info* lib = ph->libs;
 409    while (lib) {
 410       if (count == index) {
 411          return lib->name;
 412       }
 413       count++;
 414       lib = lib->next;
 415    }
 416    return NULL;
 417 }
 418 
 419 // get base address of a lib
 420 uintptr_t get_lib_base(struct ps_prochandle* ph, int index) {
 421    int count = 0;
 422    lib_info* lib = ph->libs;
 423    while (lib) {
 424       if (count == index) {
 425          return lib->base;
 426       }
 427       count++;
 428       lib = lib->next;
 429    }
 430    return (uintptr_t)NULL;
 431 }
 432 
 433 bool find_lib(struct ps_prochandle* ph, const char *lib_name) {
 434   lib_info *p = ph->libs;
 435   while (p) {
 436     if (strcmp(p->name, lib_name) == 0) {
 437       return true;
 438     }
 439     p = p->next;
 440   }
 441   return false;
 442 }
 443 
 444 struct lib_info *find_lib_by_address(struct ps_prochandle* ph, uintptr_t pc) {
 445   lib_info *p = ph->libs;
 446   while (p) {
 447     if ((p->exec_start <= pc) && (pc < p->exec_end)) {
 448       return p;
 449     }
 450     p = p->next;
 451   }
 452   return NULL;
 453 }
 454 
 455 //--------------------------------------------------------------------------
 456 // proc service functions
 457 
 458 // get process id
 459 JNIEXPORT pid_t JNICALL
 460 ps_getpid(struct ps_prochandle *ph) {
 461    return ph->pid;
 462 }
 463 
 464 // ps_pglobal_lookup() looks up the symbol sym_name in the symbol table
 465 // of the load object object_name in the target process identified by ph.
 466 // It returns the symbol's value as an address in the target process in
 467 // *sym_addr.
 468 
 469 JNIEXPORT ps_err_e JNICALL
 470 ps_pglobal_lookup(struct ps_prochandle *ph, const char *object_name,
 471                     const char *sym_name, psaddr_t *sym_addr) {
 472   *sym_addr = (psaddr_t) lookup_symbol(ph, object_name, sym_name);
 473   return (*sym_addr ? PS_OK : PS_NOSYM);
 474 }
 475 
 476 // read "size" bytes info "buf" from address "addr"
 477 JNIEXPORT ps_err_e JNICALL
 478 ps_pdread(struct ps_prochandle *ph, psaddr_t  addr,
 479                    void *buf, size_t size) {
 480   return ph->ops->p_pread(ph, (uintptr_t) addr, buf, size)? PS_OK: PS_ERR;
 481 }
 482 
 483 // write "size" bytes of data to debuggee at address "addr"
 484 JNIEXPORT ps_err_e JNICALL
 485 ps_pdwrite(struct ps_prochandle *ph, psaddr_t addr,
 486                     const void *buf, size_t size) {
 487   return ph->ops->p_pwrite(ph, (uintptr_t)addr, buf, size)? PS_OK: PS_ERR;
 488 }
 489 
 490 // ------------------------------------------------------------------------
 491 // Functions below this point are not yet implemented. They are here only
 492 // to make the linker happy.
 493 
 494 JNIEXPORT ps_err_e JNICALL
 495 ps_lsetfpregs(struct ps_prochandle *ph, lwpid_t lid, const prfpregset_t *fpregs) {
 496   print_debug("ps_lsetfpregs not implemented\n");
 497   return PS_OK;
 498 }
 499 
 500 JNIEXPORT ps_err_e JNICALL
 501 ps_lsetregs(struct ps_prochandle *ph, lwpid_t lid, const prgregset_t gregset) {
 502   print_debug("ps_lsetregs not implemented\n");
 503   return PS_OK;
 504 }
 505 
 506 JNIEXPORT ps_err_e  JNICALL
 507 ps_lgetfpregs(struct  ps_prochandle  *ph,  lwpid_t lid, prfpregset_t *fpregs) {
 508   print_debug("ps_lgetfpregs not implemented\n");
 509   return PS_OK;
 510 }
 511 
 512 JNIEXPORT ps_err_e JNICALL
 513 ps_lgetregs(struct ps_prochandle *ph, lwpid_t lid, prgregset_t gregset) {
 514   print_debug("ps_lgetfpregs not implemented\n");
 515   return PS_OK;
 516 }
 517