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