1 /*
   2  * Copyright (c) 2003, 2019, 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 
  25 #include <stdio.h>
  26 #include <stdlib.h>
  27 #include <string.h>
  28 #include <signal.h>
  29 #include <errno.h>
  30 #include <elf.h>
  31 #include <dirent.h>
  32 #include <ctype.h>
  33 #include <sys/types.h>
  34 #include <sys/wait.h>
  35 #include <sys/ptrace.h>
  36 #include <sys/uio.h>
  37 #include "libproc_impl.h"
  38 
  39 #if defined(x86_64) && !defined(amd64)
  40 #define amd64 1
  41 #endif
  42 
  43 #ifndef __WALL
  44 #define __WALL          0x40000000  // Copied from /usr/include/linux/wait.h
  45 #endif
  46 
  47 // This file has the libproc implementation specific to live process
  48 // For core files, refer to ps_core.c
  49 
  50 typedef enum {
  51   ATTACH_SUCCESS,
  52   ATTACH_FAIL,
  53   ATTACH_THREAD_DEAD
  54 } attach_state_t;
  55 
  56 static inline uintptr_t align(uintptr_t ptr, size_t size) {
  57   return (ptr & ~(size - 1));
  58 }
  59 
  60 // ---------------------------------------------
  61 // ptrace functions
  62 // ---------------------------------------------
  63 
  64 // read "size" bytes of data from "addr" within the target process.
  65 // unlike the standard ptrace() function, process_read_data() can handle
  66 // unaligned address - alignment check, if required, should be done
  67 // before calling process_read_data.
  68 
  69 static bool process_read_data(struct ps_prochandle* ph, uintptr_t addr, char *buf, size_t size) {
  70   long rslt;
  71   size_t i, words;
  72   uintptr_t end_addr = addr + size;
  73   uintptr_t aligned_addr = align(addr, sizeof(long));
  74 
  75   if (aligned_addr != addr) {
  76     char *ptr = (char *)&rslt;
  77     errno = 0;
  78     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
  79     if (errno) {
  80       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
  81       return false;
  82     }
  83     for (; aligned_addr != addr; aligned_addr++, ptr++);
  84     for (; ((intptr_t)aligned_addr % sizeof(long)) && aligned_addr < end_addr;
  85         aligned_addr++)
  86        *(buf++) = *(ptr++);
  87   }
  88 
  89   words = (end_addr - aligned_addr) / sizeof(long);
  90 
  91   // assert((intptr_t)aligned_addr % sizeof(long) == 0);
  92   for (i = 0; i < words; i++) {
  93     errno = 0;
  94     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
  95     if (errno) {
  96       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
  97       return false;
  98     }
  99     *(long *)buf = rslt;
 100     buf += sizeof(long);
 101     aligned_addr += sizeof(long);
 102   }
 103 
 104   if (aligned_addr != end_addr) {
 105     char *ptr = (char *)&rslt;
 106     errno = 0;
 107     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
 108     if (errno) {
 109       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
 110       return false;
 111     }
 112     for (; aligned_addr != end_addr; aligned_addr++)
 113        *(buf++) = *(ptr++);
 114   }
 115   return true;
 116 }
 117 
 118 // null implementation for write
 119 static bool process_write_data(struct ps_prochandle* ph,
 120                              uintptr_t addr, const char *buf , size_t size) {
 121   return false;
 122 }
 123 
 124 // "user" should be a pointer to a user_regs_struct
 125 static bool process_get_lwp_regs(struct ps_prochandle* ph, pid_t pid, struct user_regs_struct *user) {
 126   // we have already attached to all thread 'pid's, just use ptrace call
 127   // to get regset now. Note that we don't cache regset upfront for processes.
 128 // Linux on x86 and sparc are different.  On x86 ptrace(PTRACE_GETREGS, ...)
 129 // uses pointer from 4th argument and ignores 3rd argument.  On sparc it uses
 130 // pointer from 3rd argument and ignores 4th argument
 131 #define ptrace_getregs(request, pid, addr, data) ptrace(request, pid, data, addr)
 132 
 133 #if defined(_LP64) && defined(PTRACE_GETREGS64)
 134 #define PTRACE_GETREGS_REQ PTRACE_GETREGS64
 135 #elif defined(PTRACE_GETREGS)
 136 #define PTRACE_GETREGS_REQ PTRACE_GETREGS
 137 #elif defined(PT_GETREGS)
 138 #define PTRACE_GETREGS_REQ PT_GETREGS
 139 #endif
 140 
 141 #ifdef PTRACE_GETREGS_REQ
 142  if (ptrace_getregs(PTRACE_GETREGS_REQ, pid, user, NULL) < 0) {
 143    print_debug("ptrace(PTRACE_GETREGS, ...) failed for lwp %d\n", pid);
 144    return false;
 145  }
 146  return true;
 147 #elif defined(PTRACE_GETREGSET)
 148  struct iovec iov;
 149  iov.iov_base = user;
 150  iov.iov_len = sizeof(*user);
 151  if (ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, (void*) &iov) < 0) {
 152    print_debug("ptrace(PTRACE_GETREGSET, ...) failed for lwp %d\n", pid);
 153    return false;
 154  }
 155  return true;
 156 #else
 157  print_debug("ptrace(PTRACE_GETREGS, ...) not supported\n");
 158  return false;
 159 #endif
 160 
 161 }
 162 
 163 static bool ptrace_continue(pid_t pid, int signal) {
 164   // pass the signal to the process so we don't swallow it
 165   if (ptrace(PTRACE_CONT, pid, NULL, signal) < 0) {
 166     print_debug("ptrace(PTRACE_CONT, ..) failed for %d\n", pid);
 167     return false;
 168   }
 169   return true;
 170 }
 171 
 172 // waits until the ATTACH has stopped the process
 173 // by signal SIGSTOP
 174 static attach_state_t ptrace_waitpid(pid_t pid) {
 175   int ret;
 176   int status;
 177   errno = 0;
 178   while (true) {
 179     // Wait for debuggee to stop.
 180     ret = waitpid(pid, &status, 0);
 181     if (ret == -1 && errno == ECHILD) {
 182       // try cloned process.
 183       ret = waitpid(pid, &status, __WALL);
 184     }
 185     if (ret >= 0) {
 186       if (WIFSTOPPED(status)) {
 187         // Any signal will stop the thread, make sure it is SIGSTOP. Otherwise SIGSTOP
 188         // will still be pending and delivered when the process is DETACHED and the process
 189         // will go to sleep.
 190         if (WSTOPSIG(status) == SIGSTOP) {
 191           // Debuggee stopped by SIGSTOP.
 192           return ATTACH_SUCCESS;
 193         }
 194         if (!ptrace_continue(pid, WSTOPSIG(status))) {
 195           print_error("Failed to correctly attach to VM. VM might HANG! [PTRACE_CONT failed, stopped by %d]\n", WSTOPSIG(status));
 196           return ATTACH_FAIL;
 197         }
 198       } else {
 199         print_debug("waitpid(): Child process %d exited/terminated (status = 0x%x)\n", pid, status);
 200         return ATTACH_THREAD_DEAD;
 201       }
 202     } else {
 203       switch (errno) {
 204         case EINTR:
 205           continue;
 206           break;
 207         case ECHILD:
 208           print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid);
 209           return ATTACH_THREAD_DEAD;
 210         case EINVAL:
 211           print_error("waitpid() failed. Invalid options argument.\n");
 212           return ATTACH_FAIL;
 213         default:
 214           print_error("waitpid() failed. Unexpected error %d\n", errno);
 215           return ATTACH_FAIL;
 216       }
 217     } // else
 218   } // while
 219 }
 220 
 221 // checks the state of the thread/process specified by "pid", by reading
 222 // in the 'State:' value from the /proc/<pid>/status file. From the proc
 223 // man page, "Current state of the process. One of "R (running)",
 224 // "S (sleeping)", "D (disk sleep)", "T (stopped)", "T (tracing stop)",
 225 // "Z (zombie)", or "X (dead)"." Assumes that the thread is dead if we
 226 // don't find the status file or if the status is 'X' or 'Z'.
 227 static bool process_doesnt_exist(pid_t pid) {
 228   char fname[32];
 229   char buf[30];
 230   FILE *fp = NULL;
 231   const char state_string[] = "State:";
 232 
 233   sprintf(fname, "/proc/%d/status", pid);
 234   fp = fopen(fname, "r");
 235   if (fp == NULL) {
 236     print_debug("can't open /proc/%d/status file\n", pid);
 237     // Assume the thread does not exist anymore.
 238     return true;
 239   }
 240   bool found_state = false;
 241   size_t state_len = strlen(state_string);
 242   while (fgets(buf, sizeof(buf), fp) != NULL) {
 243     char *state = NULL;
 244     if (strncmp (buf, state_string, state_len) == 0) {
 245       found_state = true;
 246       state = buf + state_len;
 247       // Skip the spaces
 248       while (isspace(*state)) {
 249         state++;
 250       }
 251       // A state value of 'X' indicates that the thread is dead. 'Z'
 252       // indicates that the thread is a zombie.
 253       if (*state == 'X' || *state == 'Z') {
 254         fclose (fp);
 255         return true;
 256       }
 257       break;
 258     }
 259   }
 260   // If the state value is not 'X' or 'Z', the thread exists.
 261   if (!found_state) {
 262     // We haven't found the line beginning with 'State:'.
 263     // Assuming the thread exists.
 264     print_error("Could not find the 'State:' string in the /proc/%d/status file\n", pid);
 265   }
 266   fclose (fp);
 267   return false;
 268 }
 269 
 270 // attach to a process/thread specified by "pid"
 271 static attach_state_t ptrace_attach(pid_t pid, char* err_buf, size_t err_buf_len) {
 272   errno = 0;
 273   if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) {
 274     if (errno == EPERM || errno == ESRCH) {
 275       // Check if the process/thread is exiting or is a zombie
 276       if (process_doesnt_exist(pid)) {
 277         print_debug("Thread with pid %d does not exist\n", pid);
 278         return ATTACH_THREAD_DEAD;
 279       }
 280     }
 281     char buf[200];
 282     char* msg = strerror_r(errno, buf, sizeof(buf));
 283     snprintf(err_buf, err_buf_len, "ptrace(PTRACE_ATTACH, ..) failed for %d: %s", pid, msg);
 284     print_error("%s\n", err_buf);
 285     return ATTACH_FAIL;
 286   } else {
 287     attach_state_t wait_ret = ptrace_waitpid(pid);
 288     if (wait_ret == ATTACH_THREAD_DEAD) {
 289       print_debug("Thread with pid %d does not exist\n", pid);
 290     }
 291     return wait_ret;
 292   }
 293 }
 294 
 295 // -------------------------------------------------------
 296 // functions for obtaining library information
 297 // -------------------------------------------------------
 298 
 299 /*
 300  * splits a string _str_ into substrings with delimiter _delim_ by replacing old * delimiters with _new_delim_ (ideally, '\0'). the address of each substring
 301  * is stored in array _ptrs_ as the return value. the maximum capacity of _ptrs_ * array is specified by parameter _n_.
 302  * RETURN VALUE: total number of substrings (always <= _n_)
 303  * NOTE: string _str_ is modified if _delim_!=_new_delim_
 304  */
 305 static int split_n_str(char * str, int n, char ** ptrs, char delim, char new_delim)
 306 {
 307    int i;
 308    for(i = 0; i < n; i++) ptrs[i] = NULL;
 309    if (str == NULL || n < 1 ) return 0;
 310 
 311    i = 0;
 312 
 313    // skipping leading blanks
 314    while(*str&&*str==delim) str++;
 315 
 316    while(*str&&i<n){
 317      ptrs[i++] = str;
 318      while(*str&&*str!=delim) str++;
 319      while(*str&&*str==delim) *(str++) = new_delim;
 320    }
 321 
 322    return i;
 323 }
 324 
 325 /*
 326  * fgets without storing '\n' at the end of the string
 327  */
 328 static char * fgets_no_cr(char * buf, int n, FILE *fp)
 329 {
 330    char * rslt = fgets(buf, n, fp);
 331    if (rslt && buf && *buf){
 332        char *p = strchr(buf, '\0');
 333        if (*--p=='\n') *p='\0';
 334    }
 335    return rslt;
 336 }
 337 
 338 static bool read_lib_info(struct ps_prochandle* ph) {
 339   char fname[32];
 340   char buf[PATH_MAX];
 341   FILE *fp = NULL;
 342 
 343   sprintf(fname, "/proc/%d/maps", ph->pid);
 344   fp = fopen(fname, "r");
 345   if (fp == NULL) {
 346     print_debug("can't open /proc/%d/maps file\n", ph->pid);
 347     return false;
 348   }
 349 
 350   while(fgets_no_cr(buf, PATH_MAX, fp)){
 351     char * word[7];
 352     int nwords = split_n_str(buf, 7, word, ' ', '\0');
 353 
 354     if (nwords < 6) {
 355       // not a shared library entry. ignore.
 356       continue;
 357     }
 358 
 359     // SA does not handle the lines with patterns:
 360     //   "[stack]", "[heap]", "[vdso]", "[vsyscall]", etc.
 361     if (word[5][0] == '[') {
 362         // not a shared library entry. ignore.
 363         continue;
 364     }
 365 
 366     if (nwords > 6) {
 367       // prelink altered mapfile when the program is running.
 368       // Entries like one below have to be skipped
 369       //  /lib64/libc-2.15.so (deleted)
 370       // SO name in entries like one below have to be stripped.
 371       //  /lib64/libpthread-2.15.so.#prelink#.EECVts
 372       char *s = strstr(word[5],".#prelink#");
 373       if (s == NULL) {
 374         // No prelink keyword. skip deleted library
 375         print_debug("skip shared object %s deleted by prelink\n", word[5]);
 376         continue;
 377       }
 378 
 379       // Fall through
 380       print_debug("rectifying shared object name %s changed by prelink\n", word[5]);
 381       *s = 0;
 382     }
 383 
 384     if (find_lib(ph, word[5]) == false) {
 385        intptr_t base;
 386        lib_info* lib;
 387 #ifdef _LP64
 388        sscanf(word[0], "%lx", &base);
 389 #else
 390        sscanf(word[0], "%x", &base);
 391 #endif
 392        if ((lib = add_lib_info(ph, word[5], (uintptr_t)base)) == NULL)
 393           continue; // ignore, add_lib_info prints error
 394 
 395        // we don't need to keep the library open, symtab is already
 396        // built. Only for core dump we need to keep the fd open.
 397        close(lib->fd);
 398        lib->fd = -1;
 399     }
 400   }
 401   fclose(fp);
 402   return true;
 403 }
 404 
 405 // detach a given pid
 406 static bool ptrace_detach(pid_t pid) {
 407   if (pid && ptrace(PTRACE_DETACH, pid, NULL, NULL) < 0) {
 408     print_debug("ptrace(PTRACE_DETACH, ..) failed for %d\n", pid);
 409     return false;
 410   } else {
 411     return true;
 412   }
 413 }
 414 
 415 // detach all pids of a ps_prochandle
 416 static void detach_all_pids(struct ps_prochandle* ph) {
 417   thread_info* thr = ph->threads;
 418   while (thr) {
 419      ptrace_detach(thr->lwp_id);
 420      thr = thr->next;
 421   }
 422 }
 423 
 424 static void process_cleanup(struct ps_prochandle* ph) {
 425   detach_all_pids(ph);
 426 }
 427 
 428 static ps_prochandle_ops process_ops = {
 429   .release=  process_cleanup,
 430   .p_pread=  process_read_data,
 431   .p_pwrite= process_write_data,
 432   .get_lwp_regs= process_get_lwp_regs
 433 };
 434 
 435 // attach to the process. One and only one exposed stuff
 436 JNIEXPORT struct ps_prochandle* JNICALL
 437 Pgrab(pid_t pid, char* err_buf, size_t err_buf_len) {
 438   struct ps_prochandle* ph = NULL;
 439   thread_info* thr = NULL;
 440   attach_state_t attach_status = ATTACH_SUCCESS;
 441 
 442   if ( (ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle))) == NULL) {
 443     snprintf(err_buf, err_buf_len, "can't allocate memory for ps_prochandle");
 444     print_debug("%s\n", err_buf);
 445     return NULL;
 446   }
 447 
 448   if ((attach_status = ptrace_attach(pid, err_buf, err_buf_len)) != ATTACH_SUCCESS) {
 449     if (attach_status == ATTACH_THREAD_DEAD) {
 450        print_error("The process with pid %d does not exist.\n", pid);
 451     }
 452     free(ph);
 453     return NULL;
 454   }
 455 
 456   // initialize ps_prochandle
 457   ph->pid = pid;
 458   add_thread_info(ph, ph->pid);
 459 
 460   // initialize vtable
 461   ph->ops = &process_ops;
 462 
 463   // read library info and symbol tables, must do this before attaching threads,
 464   // as the symbols in the pthread library will be used to figure out
 465   // the list of threads within the same process.
 466   read_lib_info(ph);
 467 
 468   /*
 469    * Read thread info.
 470    * SA scans all tasks in /proc/<PID>/task to read all threads info.
 471    */
 472   char taskpath[PATH_MAX];
 473   DIR *dirp;
 474   struct dirent *entry;
 475 
 476   snprintf(taskpath, PATH_MAX, "/proc/%d/task", ph->pid);
 477   dirp = opendir(taskpath);
 478   int lwp_id;
 479   while ((entry = readdir(dirp)) != NULL) {
 480     if (*entry->d_name == '.') {
 481       continue;
 482     }
 483     lwp_id = atoi(entry->d_name);
 484     if (lwp_id == ph->pid) {
 485       continue;
 486     }
 487     if (!process_doesnt_exist(lwp_id)) {
 488       add_thread_info(ph, lwp_id);
 489     }
 490   }
 491   closedir(dirp);
 492 
 493   // attach to the threads
 494   thr = ph->threads;
 495 
 496   while (thr) {
 497     thread_info* current_thr = thr;
 498     thr = thr->next;
 499     // don't attach to the main thread again
 500     if (ph->pid != current_thr->lwp_id) {
 501       if ((attach_status = ptrace_attach(current_thr->lwp_id, err_buf, err_buf_len)) != ATTACH_SUCCESS) {
 502         if (attach_status == ATTACH_THREAD_DEAD) {
 503           // Remove this thread from the threads list
 504           delete_thread_info(ph, current_thr);
 505         }
 506         else {
 507           Prelease(ph);
 508           return NULL;
 509         } // ATTACH_THREAD_DEAD
 510       } // !ATTACH_SUCCESS
 511     }
 512   }
 513   return ph;
 514 }