1 /*
   2  * Copyright 2003-2008 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include <stdio.h>
  26 #include <stdlib.h>
  27 #include <string.h>
  28 #include <errno.h>
  29 #include <sys/ptrace.h>
  30 #include "libproc_impl.h"
  31 
  32 #if defined(x86_64) && !defined(amd64)
  33 #define amd64 1
  34 #endif
  35 
  36 #ifndef __WALL
  37 #define __WALL          0x40000000  // Copied from /usr/include/linux/wait.h
  38 #endif
  39 
  40 // This file has the libproc implementation specific to live process
  41 // For core files, refer to ps_core.c
  42 
  43 static inline uintptr_t align(uintptr_t ptr, size_t size) {
  44   return (ptr & ~(size - 1));
  45 }
  46 
  47 // ---------------------------------------------
  48 // ptrace functions
  49 // ---------------------------------------------
  50 
  51 // read "size" bytes of data from "addr" within the target process.
  52 // unlike the standard ptrace() function, process_read_data() can handle
  53 // unaligned address - alignment check, if required, should be done
  54 // before calling process_read_data.
  55 
  56 static bool process_read_data(struct ps_prochandle* ph, uintptr_t addr, char *buf, size_t size) {
  57   long rslt;
  58   size_t i, words;
  59   uintptr_t end_addr = addr + size;
  60   uintptr_t aligned_addr = align(addr, sizeof(long));
  61 
  62   if (aligned_addr != addr) {
  63     char *ptr = (char *)&rslt;
  64     errno = 0;
  65     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
  66     if (errno) {
  67       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
  68       return false;
  69     }
  70     for (; aligned_addr != addr; aligned_addr++, ptr++);
  71     for (; ((intptr_t)aligned_addr % sizeof(long)) && aligned_addr < end_addr;
  72         aligned_addr++)
  73        *(buf++) = *(ptr++);
  74   }
  75 
  76   words = (end_addr - aligned_addr) / sizeof(long);
  77 
  78   // assert((intptr_t)aligned_addr % sizeof(long) == 0);
  79   for (i = 0; i < words; i++) {
  80     errno = 0;
  81     rslt = ptrace(PTRACE_PEEKDATA, ph->pid, aligned_addr, 0);
  82     if (errno) {
  83       print_debug("ptrace(PTRACE_PEEKDATA, ..) failed for %d bytes @ %lx\n", size, addr);
  84       return false;
  85     }
  86     *(long *)buf = rslt;
  87     buf += sizeof(long);
  88     aligned_addr += sizeof(long);
  89   }
  90 
  91   if (aligned_addr != end_addr) {
  92     char *ptr = (char *)&rslt;
  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     for (; aligned_addr != end_addr; aligned_addr++)
 100        *(buf++) = *(ptr++);
 101   }
 102   return true;
 103 }
 104 
 105 // null implementation for write
 106 static bool process_write_data(struct ps_prochandle* ph,
 107                              uintptr_t addr, const char *buf , size_t size) {
 108   return false;
 109 }
 110 
 111 // "user" should be a pointer to a user_regs_struct
 112 static bool process_get_lwp_regs(struct ps_prochandle* ph, pid_t pid, struct user_regs_struct *user) {
 113   // we have already attached to all thread 'pid's, just use ptrace call
 114   // to get regset now. Note that we don't cache regset upfront for processes.
 115 // Linux on x86 and sparc are different.  On x86 ptrace(PTRACE_GETREGS, ...)
 116 // uses pointer from 4th argument and ignores 3rd argument.  On sparc it uses
 117 // pointer from 3rd argument and ignores 4th argument
 118 #if defined(sparc) || defined(sparcv9)
 119 #define ptrace_getregs(request, pid, addr, data) ptrace(request, pid, addr, data)
 120 #else
 121 #define ptrace_getregs(request, pid, addr, data) ptrace(request, pid, data, addr)
 122 #endif
 123 
 124 #ifdef _LP64
 125 #ifdef PTRACE_GETREGS64
 126 #define PTRACE_GETREGS_REQ PTRACE_GETREGS64
 127 #endif
 128 #else
 129 #if defined(PTRACE_GETREGS) || defined(PT_GETREGS)
 130 #define PTRACE_GETREGS_REQ PTRACE_GETREGS
 131 #endif
 132 #endif /* _LP64 */
 133 
 134 #ifdef PTRACE_GETREGS_REQ
 135  if (ptrace_getregs(PTRACE_GETREGS_REQ, pid, user, NULL) < 0) {
 136    print_debug("ptrace(PTRACE_GETREGS, ...) failed for lwp %d\n", pid);
 137    return false;
 138  }
 139  return true;
 140 #else
 141  print_debug("ptrace(PTRACE_GETREGS, ...) not supported\n");
 142  return false;
 143 #endif
 144 
 145 }
 146 
 147 // attach to a process/thread specified by "pid"
 148 static bool ptrace_attach(pid_t pid) {
 149   if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) {
 150     print_debug("ptrace(PTRACE_ATTACH, ..) failed for %d\n", pid);
 151     return false;
 152   } else {
 153     int ret;
 154     int status;
 155     do {
 156       // Wait for debuggee to stop.
 157       ret = waitpid(pid, &status, 0);
 158       if (ret == -1 && errno == ECHILD) {
 159         // try cloned process.
 160         ret = waitpid(pid, &status, __WALL);
 161       }
 162       if (ret >= 0) {
 163         if (WIFSTOPPED(status)) {
 164           // Debuggee stopped.
 165           return true;
 166         } else {
 167           print_debug("waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
 168           return false;
 169         }
 170       } else {
 171         switch (errno) {
 172           case EINTR:
 173             continue;
 174             break;
 175           case ECHILD:
 176             print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid);
 177             break;
 178           case EINVAL:
 179             print_debug("waitpid() failed. Invalid options argument.\n");
 180             break;
 181           default:
 182             print_debug("waitpid() failed. Unexpected error %d\n",errno);
 183         }
 184         return false;
 185       }
 186     } while(true);
 187   }
 188 }
 189 
 190 // -------------------------------------------------------
 191 // functions for obtaining library information
 192 // -------------------------------------------------------
 193 
 194 /*
 195  * splits a string _str_ into substrings with delimiter _delim_ by replacing old * delimiters with _new_delim_ (ideally, '\0'). the address of each substring
 196  * is stored in array _ptrs_ as the return value. the maximum capacity of _ptrs_ * array is specified by parameter _n_.
 197  * RETURN VALUE: total number of substrings (always <= _n_)
 198  * NOTE: string _str_ is modified if _delim_!=_new_delim_
 199  */
 200 static int split_n_str(char * str, int n, char ** ptrs, char delim, char new_delim)
 201 {
 202    int i;
 203    for(i = 0; i < n; i++) ptrs[i] = NULL;
 204    if (str == NULL || n < 1 ) return 0;
 205 
 206    i = 0;
 207 
 208    // skipping leading blanks
 209    while(*str&&*str==delim) str++;
 210 
 211    while(*str&&i<n){
 212      ptrs[i++] = str;
 213      while(*str&&*str!=delim) str++;
 214      while(*str&&*str==delim) *(str++) = new_delim;
 215    }
 216 
 217    return i;
 218 }
 219 
 220 /*
 221  * fgets without storing '\n' at the end of the string
 222  */
 223 static char * fgets_no_cr(char * buf, int n, FILE *fp)
 224 {
 225    char * rslt = fgets(buf, n, fp);
 226    if (rslt && buf && *buf){
 227        char *p = strchr(buf, '\0');
 228        if (*--p=='\n') *p='\0';
 229    }
 230    return rslt;
 231 }
 232 
 233 // callback for read_thread_info
 234 static bool add_new_thread(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id) {
 235   return add_thread_info(ph, pthread_id, lwp_id) != NULL;
 236 }
 237 
 238 static bool read_lib_info(struct ps_prochandle* ph) {
 239   char fname[32];
 240   char buf[256];
 241   FILE *fp = NULL;
 242 
 243   sprintf(fname, "/proc/%d/maps", ph->pid);
 244   fp = fopen(fname, "r");
 245   if (fp == NULL) {
 246     print_debug("can't open /proc/%d/maps file\n", ph->pid);
 247     return false;
 248   }
 249 
 250   while(fgets_no_cr(buf, 256, fp)){
 251     char * word[6];
 252     int nwords = split_n_str(buf, 6, word, ' ', '\0');
 253     if (nwords > 5 && find_lib(ph, word[5]) == false) {
 254        intptr_t base;
 255        lib_info* lib;
 256        sscanf(word[0], "%lx", &base);
 257        if ((lib = add_lib_info(ph, word[5], (uintptr_t)base)) == NULL)
 258           continue; // ignore, add_lib_info prints error
 259 
 260        // we don't need to keep the library open, symtab is already
 261        // built. Only for core dump we need to keep the fd open.
 262        close(lib->fd);
 263        lib->fd = -1;
 264     }
 265   }
 266   fclose(fp);
 267   return true;
 268 }
 269 
 270 // detach a given pid
 271 static bool ptrace_detach(pid_t pid) {
 272   if (pid && ptrace(PTRACE_DETACH, pid, NULL, NULL) < 0) {
 273     print_debug("ptrace(PTRACE_DETACH, ..) failed for %d\n", pid);
 274     return false;
 275   } else {
 276     return true;
 277   }
 278 }
 279 
 280 // detach all pids of a ps_prochandle
 281 static void detach_all_pids(struct ps_prochandle* ph) {
 282   thread_info* thr = ph->threads;
 283   while (thr) {
 284      ptrace_detach(thr->lwp_id);
 285      thr = thr->next;
 286   }
 287 }
 288 
 289 static void process_cleanup(struct ps_prochandle* ph) {
 290   detach_all_pids(ph);
 291 }
 292 
 293 static ps_prochandle_ops process_ops = {
 294   .release=  process_cleanup,
 295   .p_pread=  process_read_data,
 296   .p_pwrite= process_write_data,
 297   .get_lwp_regs= process_get_lwp_regs
 298 };
 299 
 300 // attach to the process. One and only one exposed stuff
 301 struct ps_prochandle* Pgrab(pid_t pid) {
 302   struct ps_prochandle* ph = NULL;
 303   thread_info* thr = NULL;
 304 
 305   if ( (ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle))) == NULL) {
 306      print_debug("can't allocate memory for ps_prochandle\n");
 307      return NULL;
 308   }
 309 
 310   if (ptrace_attach(pid) != true) {
 311      free(ph);
 312      return NULL;
 313   }
 314 
 315   // initialize ps_prochandle
 316   ph->pid = pid;
 317 
 318   // initialize vtable
 319   ph->ops = &process_ops;
 320 
 321   // read library info and symbol tables, must do this before attaching threads,
 322   // as the symbols in the pthread library will be used to figure out
 323   // the list of threads within the same process.
 324   read_lib_info(ph);
 325 
 326   // read thread info
 327   read_thread_info(ph, add_new_thread);
 328 
 329   // attach to the threads
 330   thr = ph->threads;
 331   while (thr) {
 332      // don't attach to the main thread again
 333      if (ph->pid != thr->lwp_id && ptrace_attach(thr->lwp_id) != true) {
 334         // even if one attach fails, we get return NULL
 335         Prelease(ph);
 336         return NULL;
 337      }
 338      thr = thr->next;
 339   }
 340   return ph;
 341 }