1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 
  22 /*
  23  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
  24  * Use is subject to license terms.
  25  *
  26  * Portions Copyright 2007 Chad Mynhier
  27  * Copyright 2012 DEY Storage Systems, Inc.  All rights reserved.
  28  * Copyright (c) 2013 by Delphix. All rights reserved.
  29  * Copyright 2015, Joyent, Inc.
  30  */
  31 
  32 #include <assert.h>
  33 #include <stdio.h>
  34 #include <stdlib.h>
  35 #include <unistd.h>
  36 #include <ctype.h>
  37 #include <fcntl.h>
  38 #include <string.h>
  39 #include <strings.h>
  40 #include <memory.h>
  41 #include <errno.h>
  42 #include <dirent.h>
  43 #include <limits.h>
  44 #include <signal.h>
  45 #include <atomic.h>
  46 #include <zone.h>
  47 #include <sys/types.h>
  48 #include <sys/uio.h>
  49 #include <sys/stat.h>
  50 #include <sys/resource.h>
  51 #include <sys/param.h>
  52 #include <sys/stack.h>
  53 #include <sys/fault.h>
  54 #include <sys/syscall.h>
  55 #include <sys/sysmacros.h>
  56 #include <sys/systeminfo.h>
  57 
  58 #include "libproc.h"
  59 #include "Pcontrol.h"
  60 #include "Putil.h"
  61 #include "P32ton.h"
  62 
  63 int     _libproc_debug;         /* set non-zero to enable debugging printfs */
  64 int     _libproc_no_qsort;      /* set non-zero to inhibit sorting */
  65                                 /* of symbol tables */
  66 int     _libproc_incore_elf;    /* only use in-core elf data */
  67 
  68 sigset_t blockable_sigs;        /* signals to block when we need to be safe */
  69 static  int     minfd;  /* minimum file descriptor returned by dupfd(fd, 0) */
  70 char    procfs_path[PATH_MAX] = "/proc";
  71 
  72 /*
  73  * Function prototypes for static routines in this module.
  74  */
  75 static  void    deadcheck(struct ps_prochandle *);
  76 static  void    restore_tracing_flags(struct ps_prochandle *);
  77 static  void    Lfree_internal(struct ps_prochandle *, struct ps_lwphandle *);
  78 static  prheader_t *read_lfile(struct ps_prochandle *, const char *);
  79 
  80 /*
  81  * Ops vector functions for live processes.
  82  */
  83 
  84 /*ARGSUSED*/
  85 static ssize_t
  86 Pread_live(struct ps_prochandle *P, void *buf, size_t n, uintptr_t addr,
  87     void *data)
  88 {
  89         return (pread(P->asfd, buf, n, (off_t)addr));
  90 }
  91 
  92 /*ARGSUSED*/
  93 static ssize_t
  94 Pwrite_live(struct ps_prochandle *P, const void *buf, size_t n, uintptr_t addr,
  95     void *data)
  96 {
  97         return (pwrite(P->asfd, buf, n, (off_t)addr));
  98 }
  99 
 100 /*ARGSUSED*/
 101 static int
 102 Pread_maps_live(struct ps_prochandle *P, prmap_t **Pmapp, ssize_t *nmapp,
 103     void *data)
 104 {
 105         char mapfile[PATH_MAX];
 106         int mapfd;
 107         struct stat statb;
 108         ssize_t nmap;
 109         prmap_t *Pmap = NULL;
 110 
 111         (void) snprintf(mapfile, sizeof (mapfile), "%s/%d/map",
 112             procfs_path, (int)P->pid);
 113         if ((mapfd = open(mapfile, O_RDONLY)) < 0 ||
 114             fstat(mapfd, &statb) != 0 ||
 115             statb.st_size < sizeof (prmap_t) ||
 116             (Pmap = malloc(statb.st_size)) == NULL ||
 117             (nmap = pread(mapfd, Pmap, statb.st_size, 0L)) <= 0 ||
 118             (nmap /= sizeof (prmap_t)) == 0) {
 119                 if (Pmap != NULL)
 120                         free(Pmap);
 121                 if (mapfd >= 0)
 122                         (void) close(mapfd);
 123                 Preset_maps(P); /* utter failure; destroy tables */
 124                 return (-1);
 125         }
 126         (void) close(mapfd);
 127 
 128         *Pmapp = Pmap;
 129         *nmapp = nmap;
 130 
 131         return (0);
 132 }
 133 
 134 /*ARGSUSED*/
 135 static void
 136 Pread_aux_live(struct ps_prochandle *P, auxv_t **auxvp, int *nauxp, void *data)
 137 {
 138         char auxfile[64];
 139         int fd;
 140         struct stat statb;
 141         auxv_t *auxv;
 142         ssize_t naux;
 143 
 144         (void) snprintf(auxfile, sizeof (auxfile), "%s/%d/auxv",
 145             procfs_path, (int)P->pid);
 146         if ((fd = open(auxfile, O_RDONLY)) < 0) {
 147                 dprintf("%s: failed to open %s: %s\n",
 148                     __func__, auxfile, strerror(errno));
 149                 return;
 150         }
 151 
 152         if (fstat(fd, &statb) == 0 &&
 153             statb.st_size >= sizeof (auxv_t) &&
 154             (auxv = malloc(statb.st_size + sizeof (auxv_t))) != NULL) {
 155                 if ((naux = read(fd, auxv, statb.st_size)) < 0 ||
 156                     (naux /= sizeof (auxv_t)) < 1) {
 157                         dprintf("%s: read failed: %s\n",
 158                             __func__, strerror(errno));
 159                         free(auxv);
 160                 } else {
 161                         auxv[naux].a_type = AT_NULL;
 162                         auxv[naux].a_un.a_val = 0L;
 163 
 164                         *auxvp = auxv;
 165                         *nauxp = (int)naux;
 166                 }
 167         }
 168 
 169         (void) close(fd);
 170 }
 171 
 172 /*ARGSUSED*/
 173 static int
 174 Pcred_live(struct ps_prochandle *P, prcred_t *pcrp, int ngroups, void *data)
 175 {
 176         return (proc_get_cred(P->pid, pcrp, ngroups));
 177 }
 178 
 179 /*ARGSUSED*/
 180 static int
 181 Ppriv_live(struct ps_prochandle *P, prpriv_t **pprv, void *data)
 182 {
 183         prpriv_t *pp;
 184 
 185         pp = proc_get_priv(P->pid);
 186         if (pp == NULL) {
 187                 return (-1);
 188         }
 189 
 190         *pprv = pp;
 191         return (0);
 192 }
 193 
 194 /*ARGSUSED*/
 195 static const psinfo_t *
 196 Ppsinfo_live(struct ps_prochandle *P, psinfo_t *psinfo, void *data)
 197 {
 198         if (proc_get_psinfo(P->pid, psinfo) == -1)
 199                 return (NULL);
 200 
 201         return (psinfo);
 202 }
 203 
 204 /*ARGSUSED*/
 205 static prheader_t *
 206 Plstatus_live(struct ps_prochandle *P, void *data)
 207 {
 208         return (read_lfile(P, "lstatus"));
 209 }
 210 
 211 /*ARGSUSED*/
 212 static prheader_t *
 213 Plpsinfo_live(struct ps_prochandle *P, void *data)
 214 {
 215         return (read_lfile(P, "lpsinfo"));
 216 }
 217 
 218 /*ARGSUSED*/
 219 static char *
 220 Pplatform_live(struct ps_prochandle *P, char *s, size_t n, void *data)
 221 {
 222         if (sysinfo(SI_PLATFORM, s, n) == -1)
 223                 return (NULL);
 224         return (s);
 225 }
 226 
 227 /*ARGSUSED*/
 228 static int
 229 Puname_live(struct ps_prochandle *P, struct utsname *u, void *data)
 230 {
 231         return (uname(u));
 232 }
 233 
 234 /*ARGSUSED*/
 235 static char *
 236 Pzonename_live(struct ps_prochandle *P, char *s, size_t n, void *data)
 237 {
 238         if (getzonenamebyid(P->status.pr_zoneid, s, n) < 0)
 239                 return (NULL);
 240         s[n - 1] = '\0';
 241         return (s);
 242 }
 243 
 244 /*
 245  * Callback function for Pfindexec().  We return a match if we can stat the
 246  * suggested pathname and confirm its device and inode number match our
 247  * previous information about the /proc/<pid>/object/a.out file.
 248  */
 249 static int
 250 stat_exec(const char *path, void *arg)
 251 {
 252         struct stat64 *stp = arg;
 253         struct stat64 st;
 254 
 255         return (stat64(path, &st) == 0 && S_ISREG(st.st_mode) &&
 256             stp->st_dev == st.st_dev && stp->st_ino == st.st_ino);
 257 }
 258 
 259 /*ARGSUSED*/
 260 static char *
 261 Pexecname_live(struct ps_prochandle *P, char *buf, size_t buflen, void *data)
 262 {
 263         char exec_name[PATH_MAX];
 264         char cwd[PATH_MAX];
 265         char proc_cwd[64];
 266         struct stat64 st;
 267         int ret;
 268 
 269         /*
 270          * Try to get the path information first.
 271          */
 272         (void) snprintf(exec_name, sizeof (exec_name),
 273             "%s/%d/path/a.out", procfs_path, (int)P->pid);
 274         if ((ret = readlink(exec_name, buf, buflen - 1)) > 0) {
 275                 buf[ret] = '\0';
 276                 (void) Pfindobj(P, buf, buf, buflen);
 277                 return (buf);
 278         }
 279 
 280         /*
 281          * Stat the executable file so we can compare Pfindexec's
 282          * suggestions to the actual device and inode number.
 283          */
 284         (void) snprintf(exec_name, sizeof (exec_name),
 285             "%s/%d/object/a.out", procfs_path, (int)P->pid);
 286 
 287         if (stat64(exec_name, &st) != 0 || !S_ISREG(st.st_mode))
 288                 return (NULL);
 289 
 290         /*
 291          * Attempt to figure out the current working directory of the
 292          * target process.  This only works if the target process has
 293          * not changed its current directory since it was exec'd.
 294          */
 295         (void) snprintf(proc_cwd, sizeof (proc_cwd),
 296             "%s/%d/path/cwd", procfs_path, (int)P->pid);
 297 
 298         if ((ret = readlink(proc_cwd, cwd, PATH_MAX - 1)) > 0)
 299                 cwd[ret] = '\0';
 300 
 301         (void) Pfindexec(P, ret > 0 ? cwd : NULL, stat_exec, &st);
 302 
 303         return (NULL);
 304 }
 305 
 306 #if defined(__i386) || defined(__amd64)
 307 /*ARGSUSED*/
 308 static int
 309 Pldt_live(struct ps_prochandle *P, struct ssd *pldt, int nldt, void *data)
 310 {
 311         return (proc_get_ldt(P->pid, pldt, nldt));
 312 }
 313 #endif
 314 
 315 static const ps_ops_t P_live_ops = {
 316         .pop_pread      = Pread_live,
 317         .pop_pwrite     = Pwrite_live,
 318         .pop_read_maps  = Pread_maps_live,
 319         .pop_read_aux   = Pread_aux_live,
 320         .pop_cred       = Pcred_live,
 321         .pop_priv       = Ppriv_live,
 322         .pop_psinfo     = Ppsinfo_live,
 323         .pop_lstatus    = Plstatus_live,
 324         .pop_lpsinfo    = Plpsinfo_live,
 325         .pop_platform   = Pplatform_live,
 326         .pop_uname      = Puname_live,
 327         .pop_zonename   = Pzonename_live,
 328         .pop_execname   = Pexecname_live,
 329 #if defined(__i386) || defined(__amd64)
 330         .pop_ldt        = Pldt_live
 331 #endif
 332 };
 333 
 334 /*
 335  * This is the library's .init handler.
 336  */
 337 #pragma init(_libproc_init)
 338 void
 339 _libproc_init(void)
 340 {
 341         const char *root;
 342 
 343         _libproc_debug = getenv("LIBPROC_DEBUG") != NULL;
 344         _libproc_no_qsort = getenv("LIBPROC_NO_QSORT") != NULL;
 345         _libproc_incore_elf = getenv("LIBPROC_INCORE_ELF") != NULL;
 346 
 347         if ((root = zone_get_nroot()) != NULL)
 348                 (void) snprintf(procfs_path, sizeof (procfs_path), "%s/proc",
 349                     root);
 350 
 351         (void) sigfillset(&blockable_sigs);
 352         (void) sigdelset(&blockable_sigs, SIGKILL);
 353         (void) sigdelset(&blockable_sigs, SIGSTOP);
 354 }
 355 
 356 void
 357 Pset_procfs_path(const char *path)
 358 {
 359         (void) snprintf(procfs_path, sizeof (procfs_path), "%s", path);
 360 }
 361 
 362 /*
 363  * Call set_minfd() once before calling dupfd() several times.
 364  * We assume that the application will not reduce its current file
 365  * descriptor limit lower than 512 once it has set at least that value.
 366  */
 367 int
 368 set_minfd(void)
 369 {
 370         static mutex_t minfd_lock = DEFAULTMUTEX;
 371         struct rlimit rlim;
 372         int fd;
 373 
 374         if ((fd = minfd) < 256) {
 375                 (void) mutex_lock(&minfd_lock);
 376                 if ((fd = minfd) < 256) {
 377                         if (getrlimit(RLIMIT_NOFILE, &rlim) != 0)
 378                                 rlim.rlim_cur = rlim.rlim_max = 0;
 379                         if (rlim.rlim_cur >= 512)
 380                                 fd = 256;
 381                         else if ((fd = rlim.rlim_cur / 2) < 3)
 382                                 fd = 3;
 383                         membar_producer();
 384                         minfd = fd;
 385                 }
 386                 (void) mutex_unlock(&minfd_lock);
 387         }
 388         return (fd);
 389 }
 390 
 391 int
 392 dupfd(int fd, int dfd)
 393 {
 394         int mfd;
 395 
 396         /*
 397          * Make fd be greater than 255 (the 32-bit stdio limit),
 398          * or at least make it greater than 2 so that the
 399          * program will work when spawned by init(1m).
 400          * Also, if dfd is non-zero, dup the fd to be dfd.
 401          */
 402         if ((mfd = minfd) == 0)
 403                 mfd = set_minfd();
 404         if (dfd > 0 || (0 <= fd && fd < mfd)) {
 405                 if (dfd <= 0)
 406                         dfd = mfd;
 407                 dfd = fcntl(fd, F_DUPFD, dfd);
 408                 (void) close(fd);
 409                 fd = dfd;
 410         }
 411         /*
 412          * Mark it close-on-exec so any created process doesn't inherit it.
 413          */
 414         if (fd >= 0)
 415                 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
 416         return (fd);
 417 }
 418 
 419 /*
 420  * Create a new controlled process.
 421  * Leave it stopped on successful exit from exec() or execve().
 422  * Return an opaque pointer to its process control structure.
 423  * Return NULL if process cannot be created (fork()/exec() not successful).
 424  */
 425 struct ps_prochandle *
 426 Pxcreate(const char *file,      /* executable file name */
 427         char *const *argv,      /* argument vector */
 428         char *const *envp,      /* environment */
 429         int *perr,      /* pointer to error return code */
 430         char *path,     /* if non-null, holds exec path name on return */
 431         size_t len)     /* size of the path buffer */
 432 {
 433         char execpath[PATH_MAX];
 434         char procname[PATH_MAX];
 435         struct ps_prochandle *P;
 436         pid_t pid;
 437         int fd;
 438         char *fname;
 439         int rc;
 440         int lasterrno = 0;
 441 
 442         if (len == 0)   /* zero length, no path */
 443                 path = NULL;
 444         if (path != NULL)
 445                 *path = '\0';
 446 
 447         if ((P = malloc(sizeof (struct ps_prochandle))) == NULL) {
 448                 *perr = C_STRANGE;
 449                 return (NULL);
 450         }
 451 
 452         if ((pid = fork1()) == -1) {
 453                 free(P);
 454                 *perr = C_FORK;
 455                 return (NULL);
 456         }
 457 
 458         if (pid == 0) {                 /* child process */
 459                 id_t id;
 460                 extern char **environ;
 461 
 462                 /*
 463                  * If running setuid or setgid, reset credentials to normal.
 464                  */
 465                 if ((id = getgid()) != getegid())
 466                         (void) setgid(id);
 467                 if ((id = getuid()) != geteuid())
 468                         (void) setuid(id);
 469 
 470                 Pcreate_callback(P);    /* execute callback (see below) */
 471                 (void) pause();         /* wait for PRSABORT from parent */
 472 
 473                 /*
 474                  * This is ugly.  There is no execvep() function that takes a
 475                  * path and an environment.  We cheat here by replacing the
 476                  * global 'environ' variable right before we call this.
 477                  */
 478                 if (envp)
 479                         environ = (char **)envp;
 480 
 481                 (void) execvp(file, argv);  /* execute the program */
 482                 _exit(127);
 483         }
 484 
 485         /*
 486          * Initialize the process structure.
 487          */
 488         (void) memset(P, 0, sizeof (*P));
 489         (void) mutex_init(&P->proc_lock, USYNC_THREAD, NULL);
 490         P->flags |= CREATED;
 491         P->state = PS_RUN;
 492         P->pid = pid;
 493         P->asfd = -1;
 494         P->ctlfd = -1;
 495         P->statfd = -1;
 496         P->agentctlfd = -1;
 497         P->agentstatfd = -1;
 498         Pinit_ops(&P->ops, &P_live_ops);
 499         Pinitsym(P);
 500 
 501         /*
 502          * Open the /proc/pid files.
 503          */
 504         (void) snprintf(procname, sizeof (procname), "%s/%d/",
 505             procfs_path, (int)pid);
 506         fname = procname + strlen(procname);
 507         (void) set_minfd();
 508 
 509         /*
 510          * Exclusive write open advises others not to interfere.
 511          * There is no reason for any of these open()s to fail.
 512          */
 513         (void) strcpy(fname, "as");
 514         if ((fd = open(procname, (O_RDWR|O_EXCL))) < 0 ||
 515             (fd = dupfd(fd, 0)) < 0) {
 516                 dprintf("Pcreate: failed to open %s: %s\n",
 517                     procname, strerror(errno));
 518                 rc = C_STRANGE;
 519                 goto bad;
 520         }
 521         P->asfd = fd;
 522 
 523         (void) strcpy(fname, "status");
 524         if ((fd = open(procname, O_RDONLY)) < 0 ||
 525             (fd = dupfd(fd, 0)) < 0) {
 526                 dprintf("Pcreate: failed to open %s: %s\n",
 527                     procname, strerror(errno));
 528                 rc = C_STRANGE;
 529                 goto bad;
 530         }
 531         P->statfd = fd;
 532 
 533         (void) strcpy(fname, "ctl");
 534         if ((fd = open(procname, O_WRONLY)) < 0 ||
 535             (fd = dupfd(fd, 0)) < 0) {
 536                 dprintf("Pcreate: failed to open %s: %s\n",
 537                     procname, strerror(errno));
 538                 rc = C_STRANGE;
 539                 goto bad;
 540         }
 541         P->ctlfd = fd;
 542 
 543         (void) Pstop(P, 0);     /* stop the controlled process */
 544 
 545         /*
 546          * Wait for process to sleep in pause().
 547          * If the process has already called pause(), then it should be
 548          * stopped (PR_REQUESTED) while asleep in pause and we are done.
 549          * Else we set up to catch entry/exit to pause() and set the process
 550          * running again, expecting it to stop when it reaches pause().
 551          * There is no reason for this to fail other than an interrupt.
 552          */
 553         (void) Psysentry(P, SYS_pause, 1);
 554         (void) Psysexit(P, SYS_pause, 1);
 555         for (;;) {
 556                 if (P->state == PS_STOP &&
 557                     P->status.pr_lwp.pr_syscall == SYS_pause &&
 558                     (P->status.pr_lwp.pr_why == PR_REQUESTED ||
 559                     P->status.pr_lwp.pr_why == PR_SYSENTRY ||
 560                     P->status.pr_lwp.pr_why == PR_SYSEXIT))
 561                         break;
 562 
 563                 if (P->state != PS_STOP ||   /* interrupt or process died */
 564                     Psetrun(P, 0, 0) != 0) {    /* can't restart */
 565                         if (errno == EINTR || errno == ERESTART)
 566                                 rc = C_INTR;
 567                         else {
 568                                 dprintf("Pcreate: Psetrun failed: %s\n",
 569                                     strerror(errno));
 570                                 rc = C_STRANGE;
 571                         }
 572                         goto bad;
 573                 }
 574 
 575                 (void) Pwait(P, 0);
 576         }
 577         (void) Psysentry(P, SYS_pause, 0);
 578         (void) Psysexit(P, SYS_pause, 0);
 579 
 580         /*
 581          * Kick the process off the pause() and catch
 582          * it again on entry to exec() or exit().
 583          */
 584         (void) Psysentry(P, SYS_exit, 1);
 585         (void) Psysentry(P, SYS_execve, 1);
 586         if (Psetrun(P, 0, PRSABORT) == -1) {
 587                 dprintf("Pcreate: Psetrun failed: %s\n", strerror(errno));
 588                 rc = C_STRANGE;
 589                 goto bad;
 590         }
 591         (void) Pwait(P, 0);
 592         if (P->state != PS_STOP) {
 593                 dprintf("Pcreate: Pwait failed: %s\n", strerror(errno));
 594                 rc = C_STRANGE;
 595                 goto bad;
 596         }
 597 
 598         /*
 599          * Move the process through instances of failed exec()s
 600          * to reach the point of stopped on successful exec().
 601          */
 602         (void) Psysexit(P, SYS_execve, TRUE);
 603 
 604         while (P->state == PS_STOP &&
 605             P->status.pr_lwp.pr_why == PR_SYSENTRY &&
 606             P->status.pr_lwp.pr_what == SYS_execve) {
 607                 /*
 608                  * Fetch the exec path name now, before we complete
 609                  * the exec().  We may lose the process and be unable
 610                  * to get the information later.
 611                  */
 612                 (void) Pread_string(P, execpath, sizeof (execpath),
 613                     (off_t)P->status.pr_lwp.pr_sysarg[0]);
 614                 if (path != NULL)
 615                         (void) strncpy(path, execpath, len);
 616                 /*
 617                  * Set the process running and wait for
 618                  * it to stop on exit from the exec().
 619                  */
 620                 (void) Psetrun(P, 0, 0);
 621                 (void) Pwait(P, 0);
 622 
 623                 if (P->state == PS_LOST &&           /* we lost control */
 624                     Preopen(P) != 0) {          /* and we can't get it back */
 625                         rc = C_PERM;
 626                         goto bad;
 627                 }
 628 
 629                 /*
 630                  * If the exec() failed, continue the loop, expecting
 631                  * there to be more attempts to exec(), based on PATH.
 632                  */
 633                 if (P->state == PS_STOP &&
 634                     P->status.pr_lwp.pr_why == PR_SYSEXIT &&
 635                     P->status.pr_lwp.pr_what == SYS_execve &&
 636                     (lasterrno = P->status.pr_lwp.pr_errno) != 0) {
 637                         /*
 638                          * The exec() failed.  Set the process running and
 639                          * wait for it to stop on entry to the next exec().
 640                          */
 641                         (void) Psetrun(P, 0, 0);
 642                         (void) Pwait(P, 0);
 643 
 644                         continue;
 645                 }
 646                 break;
 647         }
 648 
 649         if (P->state == PS_STOP &&
 650             P->status.pr_lwp.pr_why == PR_SYSEXIT &&
 651             P->status.pr_lwp.pr_what == SYS_execve &&
 652             P->status.pr_lwp.pr_errno == 0) {
 653                 /*
 654                  * The process is stopped on successful exec() or execve().
 655                  * Turn off all tracing flags and return success.
 656                  */
 657                 restore_tracing_flags(P);
 658 #ifndef _LP64
 659                 /* We must be a 64-bit process to deal with a 64-bit process */
 660                 if (P->status.pr_dmodel == PR_MODEL_LP64) {
 661                         rc = C_LP64;
 662                         goto bad;
 663                 }
 664 #endif
 665                 /*
 666                  * Set run-on-last-close so the controlled process
 667                  * runs even if we die on a signal.
 668                  */
 669                 (void) Psetflags(P, PR_RLC);
 670                 *perr = 0;
 671                 return (P);
 672         }
 673 
 674         rc = lasterrno == ENOENT ? C_NOENT : C_NOEXEC;
 675 
 676 bad:
 677         (void) kill(pid, SIGKILL);
 678         if (path != NULL && rc != C_PERM && rc != C_LP64)
 679                 *path = '\0';
 680         Pfree(P);
 681         *perr = rc;
 682         return (NULL);
 683 }
 684 
 685 struct ps_prochandle *
 686 Pcreate(
 687         const char *file,       /* executable file name */
 688         char *const *argv,      /* argument vector */
 689         int *perr,      /* pointer to error return code */
 690         char *path,     /* if non-null, holds exec path name on return */
 691         size_t len)     /* size of the path buffer */
 692 {
 693         return (Pxcreate(file, argv, NULL, perr, path, len));
 694 }
 695 
 696 /*
 697  * Return a printable string corresponding to a Pcreate() error return.
 698  */
 699 const char *
 700 Pcreate_error(int error)
 701 {
 702         const char *str;
 703 
 704         switch (error) {
 705         case C_FORK:
 706                 str = "cannot fork";
 707                 break;
 708         case C_PERM:
 709                 str = "file is set-id or unreadable";
 710                 break;
 711         case C_NOEXEC:
 712                 str = "cannot execute file";
 713                 break;
 714         case C_INTR:
 715                 str = "operation interrupted";
 716                 break;
 717         case C_LP64:
 718                 str = "program is _LP64, self is not";
 719                 break;
 720         case C_STRANGE:
 721                 str = "unanticipated system error";
 722                 break;
 723         case C_NOENT:
 724                 str = "cannot find executable file";
 725                 break;
 726         default:
 727                 str = "unknown error";
 728                 break;
 729         }
 730 
 731         return (str);
 732 }
 733 
 734 /*
 735  * Callback to execute in each child process created with Pcreate() after fork
 736  * but before it execs the new process image.  By default, we do nothing, but
 737  * by calling this function we allow the client program to define its own
 738  * version of the function which will interpose on our empty default.  This
 739  * may be useful for clients that need to modify signal dispositions, terminal
 740  * attributes, or process group and session properties for each new victim.
 741  */
 742 /*ARGSUSED*/
 743 void
 744 Pcreate_callback(struct ps_prochandle *P)
 745 {
 746         /* nothing to do here */
 747 }
 748 
 749 /*
 750  * Grab an existing process.
 751  * Return an opaque pointer to its process control structure.
 752  *
 753  * pid:         UNIX process ID.
 754  * flags:
 755  *      PGRAB_RETAIN    Retain tracing flags (default clears all tracing flags).
 756  *      PGRAB_FORCE     Grab regardless of whether process is already traced.
 757  *      PGRAB_RDONLY    Open the address space file O_RDONLY instead of O_RDWR,
 758  *                      and do not open the process control file.
 759  *      PGRAB_NOSTOP    Open the process but do not force it to stop.
 760  * perr:        pointer to error return code.
 761  */
 762 struct ps_prochandle *
 763 Pgrab(pid_t pid, int flags, int *perr)
 764 {
 765         struct ps_prochandle *P;
 766         int fd, omode;
 767         char procname[PATH_MAX];
 768         char *fname;
 769         int rc = 0;
 770 
 771         /*
 772          * PGRAB_RDONLY means that we do not open the /proc/<pid>/control file,
 773          * and so it implies RETAIN and NOSTOP since both require control.
 774          */
 775         if (flags & PGRAB_RDONLY)
 776                 flags |= PGRAB_RETAIN | PGRAB_NOSTOP;
 777 
 778         if ((P = malloc(sizeof (struct ps_prochandle))) == NULL) {
 779                 *perr = G_STRANGE;
 780                 return (NULL);
 781         }
 782 
 783         P->asfd = -1;
 784         P->ctlfd = -1;
 785         P->statfd = -1;
 786 
 787 again:  /* Come back here if we lose it in the Window of Vulnerability */
 788         if (P->ctlfd >= 0)
 789                 (void) close(P->ctlfd);
 790         if (P->asfd >= 0)
 791                 (void) close(P->asfd);
 792         if (P->statfd >= 0)
 793                 (void) close(P->statfd);
 794         (void) memset(P, 0, sizeof (*P));
 795         (void) mutex_init(&P->proc_lock, USYNC_THREAD, NULL);
 796         P->ctlfd = -1;
 797         P->asfd = -1;
 798         P->statfd = -1;
 799         P->agentctlfd = -1;
 800         P->agentstatfd = -1;
 801         Pinit_ops(&P->ops, &P_live_ops);
 802         Pinitsym(P);
 803 
 804         /*
 805          * Open the /proc/pid files
 806          */
 807         (void) snprintf(procname, sizeof (procname), "%s/%d/",
 808             procfs_path, (int)pid);
 809         fname = procname + strlen(procname);
 810         (void) set_minfd();
 811 
 812         /*
 813          * Request exclusive open to avoid grabbing someone else's
 814          * process and to prevent others from interfering afterwards.
 815          * If this fails and the 'PGRAB_FORCE' flag is set, attempt to
 816          * open non-exclusively.
 817          */
 818         (void) strcpy(fname, "as");
 819         omode = (flags & PGRAB_RDONLY) ? O_RDONLY : O_RDWR;
 820 
 821         if (((fd = open(procname, omode | O_EXCL)) < 0 &&
 822             (fd = ((flags & PGRAB_FORCE)? open(procname, omode) : -1)) < 0) ||
 823             (fd = dupfd(fd, 0)) < 0) {
 824                 switch (errno) {
 825                 case ENOENT:
 826                         rc = G_NOPROC;
 827                         break;
 828                 case EACCES:
 829                 case EPERM:
 830                         rc = G_PERM;
 831                         break;
 832                 case EMFILE:
 833                         rc = G_NOFD;
 834                         break;
 835                 case EBUSY:
 836                         if (!(flags & PGRAB_FORCE) || geteuid() != 0) {
 837                                 rc = G_BUSY;
 838                                 break;
 839                         }
 840                         /* FALLTHROUGH */
 841                 default:
 842                         dprintf("Pgrab: failed to open %s: %s\n",
 843                             procname, strerror(errno));
 844                         rc = G_STRANGE;
 845                         break;
 846                 }
 847                 goto err;
 848         }
 849         P->asfd = fd;
 850 
 851         (void) strcpy(fname, "status");
 852         if ((fd = open(procname, O_RDONLY)) < 0 ||
 853             (fd = dupfd(fd, 0)) < 0) {
 854                 switch (errno) {
 855                 case ENOENT:
 856                         rc = G_NOPROC;
 857                         break;
 858                 case EMFILE:
 859                         rc = G_NOFD;
 860                         break;
 861                 default:
 862                         dprintf("Pgrab: failed to open %s: %s\n",
 863                             procname, strerror(errno));
 864                         rc = G_STRANGE;
 865                         break;
 866                 }
 867                 goto err;
 868         }
 869         P->statfd = fd;
 870 
 871         if (!(flags & PGRAB_RDONLY)) {
 872                 (void) strcpy(fname, "ctl");
 873                 if ((fd = open(procname, O_WRONLY)) < 0 ||
 874                     (fd = dupfd(fd, 0)) < 0) {
 875                         switch (errno) {
 876                         case ENOENT:
 877                                 rc = G_NOPROC;
 878                                 break;
 879                         case EMFILE:
 880                                 rc = G_NOFD;
 881                                 break;
 882                         default:
 883                                 dprintf("Pgrab: failed to open %s: %s\n",
 884                                     procname, strerror(errno));
 885                                 rc = G_STRANGE;
 886                                 break;
 887                         }
 888                         goto err;
 889                 }
 890                 P->ctlfd = fd;
 891         }
 892 
 893         P->state = PS_RUN;
 894         P->pid = pid;
 895 
 896         /*
 897          * We are now in the Window of Vulnerability (WoV).  The process may
 898          * exec() a setuid/setgid or unreadable object file between the open()
 899          * and the PCSTOP.  We will get EAGAIN in this case and must start over.
 900          * As Pstopstatus will trigger the first read() from a /proc file,
 901          * we also need to handle EOVERFLOW here when 32-bit as an indicator
 902          * that this process is 64-bit.  Finally, if the process has become
 903          * a zombie (PS_UNDEAD) while we were trying to grab it, just remain
 904          * silent about this and pretend there was no process.
 905          */
 906         if (Pstopstatus(P, PCNULL, 0) != 0) {
 907 #ifndef _LP64
 908                 if (errno == EOVERFLOW) {
 909                         rc = G_LP64;
 910                         goto err;
 911                 }
 912 #endif
 913                 if (P->state == PS_LOST) {   /* WoV */
 914                         (void) mutex_destroy(&P->proc_lock);
 915                         goto again;
 916                 }
 917 
 918                 if (P->state == PS_UNDEAD)
 919                         rc = G_NOPROC;
 920                 else
 921                         rc = G_STRANGE;
 922 
 923                 goto err;
 924         }
 925 
 926         /*
 927          * If the process is a system process, we can't control it even as root
 928          */
 929         if (P->status.pr_flags & PR_ISSYS) {
 930                 rc = G_SYS;
 931                 goto err;
 932         }
 933 #ifndef _LP64
 934         /*
 935          * We must be a 64-bit process to deal with a 64-bit process
 936          */
 937         if (P->status.pr_dmodel == PR_MODEL_LP64) {
 938                 rc = G_LP64;
 939                 goto err;
 940         }
 941 #endif
 942 
 943         /*
 944          * Remember the status for use by Prelease().
 945          */
 946         P->orig_status = P->status;       /* structure copy */
 947 
 948         /*
 949          * Before stopping the process, make sure we are not grabbing ourselves.
 950          * If we are, make sure we are doing it PGRAB_RDONLY.
 951          */
 952         if (pid == getpid()) {
 953                 /*
 954                  * Verify that the process is really ourself:
 955                  * Set a magic number, read it through the
 956                  * /proc file and see if the results match.
 957                  */
 958                 uint32_t magic1 = 0;
 959                 uint32_t magic2 = 2;
 960 
 961                 errno = 0;
 962 
 963                 if (Pread(P, &magic2, sizeof (magic2), (uintptr_t)&magic1)
 964                     == sizeof (magic2) &&
 965                     magic2 == 0 &&
 966                     (magic1 = 0xfeedbeef) &&
 967                     Pread(P, &magic2, sizeof (magic2), (uintptr_t)&magic1)
 968                     == sizeof (magic2) &&
 969                     magic2 == 0xfeedbeef &&
 970                     !(flags & PGRAB_RDONLY)) {
 971                         rc = G_SELF;
 972                         goto err;
 973                 }
 974         }
 975 
 976         /*
 977          * If the process is already stopped or has been directed
 978          * to stop via /proc, do not set run-on-last-close.
 979          */
 980         if (!(P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) &&
 981             !(flags & PGRAB_RDONLY)) {
 982                 /*
 983                  * Mark the process run-on-last-close so
 984                  * it runs even if we die from SIGKILL.
 985                  */
 986                 if (Psetflags(P, PR_RLC) != 0) {
 987                         if (errno == EAGAIN) {  /* WoV */
 988                                 (void) mutex_destroy(&P->proc_lock);
 989                                 goto again;
 990                         }
 991                         if (errno == ENOENT)    /* No complaint about zombies */
 992                                 rc = G_ZOMB;
 993                         else {
 994                                 dprintf("Pgrab: failed to set RLC\n");
 995                                 rc = G_STRANGE;
 996                         }
 997                         goto err;
 998                 }
 999         }
1000 
1001         /*
1002          * If a stop directive is pending and the process has not yet stopped,
1003          * then synchronously wait for the stop directive to take effect.
1004          * Limit the time spent waiting for the process to stop by iterating
1005          * at most 10 times. The time-out of 20 ms corresponds to the time
1006          * between sending the stop directive and the process actually stopped
1007          * as measured by DTrace on a slow, busy system. If the process doesn't
1008          * stop voluntarily, clear the PR_DSTOP flag so that the code below
1009          * forces the process to stop.
1010          */
1011         if (!(flags & PGRAB_RDONLY)) {
1012                 int niter = 0;
1013                 while ((P->status.pr_lwp.pr_flags & (PR_STOPPED|PR_DSTOP)) ==
1014                     PR_DSTOP && niter < 10 &&
1015                     Pstopstatus(P, PCTWSTOP, 20) != 0) {
1016                         niter++;
1017                         if (flags & PGRAB_NOSTOP)
1018                                 break;
1019                 }
1020                 if (niter == 10 && !(flags & PGRAB_NOSTOP)) {
1021                         /* Try it harder down below */
1022                         P->status.pr_lwp.pr_flags &= ~PR_DSTOP;
1023                 }
1024         }
1025 
1026         /*
1027          * If the process is not already stopped or directed to stop
1028          * and PGRAB_NOSTOP was not specified, stop the process now.
1029          */
1030         if (!(P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) &&
1031             !(flags & PGRAB_NOSTOP)) {
1032                 /*
1033                  * Stop the process, get its status and signal/syscall masks.
1034                  */
1035                 if (((P->status.pr_lwp.pr_flags & PR_STOPPED) &&
1036                     Pstopstatus(P, PCDSTOP, 0) != 0) ||
1037                     Pstopstatus(P, PCSTOP, 2000) != 0) {
1038 #ifndef _LP64
1039                         if (errno == EOVERFLOW) {
1040                                 rc = G_LP64;
1041                                 goto err;
1042                         }
1043 #endif
1044                         if (P->state == PS_LOST) {   /* WoV */
1045                                 (void) mutex_destroy(&P->proc_lock);
1046                                 goto again;
1047                         }
1048                         if ((errno != EINTR && errno != ERESTART) ||
1049                             (P->state != PS_STOP &&
1050                             !(P->status.pr_flags & PR_DSTOP))) {
1051                                 if (P->state != PS_RUN && errno != ENOENT) {
1052                                         dprintf("Pgrab: failed to PCSTOP\n");
1053                                         rc = G_STRANGE;
1054                                 } else {
1055                                         rc = G_ZOMB;
1056                                 }
1057                                 goto err;
1058                         }
1059                 }
1060 
1061                 /*
1062                  * Process should now either be stopped via /proc or there
1063                  * should be an outstanding stop directive.
1064                  */
1065                 if (!(P->status.pr_flags & (PR_ISTOP|PR_DSTOP))) {
1066                         dprintf("Pgrab: process is not stopped\n");
1067                         rc = G_STRANGE;
1068                         goto err;
1069                 }
1070 #ifndef _LP64
1071                 /*
1072                  * Test this again now because the 32-bit victim process may
1073                  * have exec'd a 64-bit process in the meantime.
1074                  */
1075                 if (P->status.pr_dmodel == PR_MODEL_LP64) {
1076                         rc = G_LP64;
1077                         goto err;
1078                 }
1079 #endif
1080         }
1081 
1082         /*
1083          * Cancel all tracing flags unless the PGRAB_RETAIN flag is set.
1084          */
1085         if (!(flags & PGRAB_RETAIN)) {
1086                 (void) Psysentry(P, 0, FALSE);
1087                 (void) Psysexit(P, 0, FALSE);
1088                 (void) Psignal(P, 0, FALSE);
1089                 (void) Pfault(P, 0, FALSE);
1090                 Psync(P);
1091         }
1092 
1093         *perr = 0;
1094         return (P);
1095 
1096 err:
1097         Pfree(P);
1098         *perr = rc;
1099         return (NULL);
1100 }
1101 
1102 /*
1103  * Return a printable string corresponding to a Pgrab() error return.
1104  */
1105 const char *
1106 Pgrab_error(int error)
1107 {
1108         const char *str;
1109 
1110         switch (error) {
1111         case G_NOPROC:
1112                 str = "no such process";
1113                 break;
1114         case G_NOCORE:
1115                 str = "no such core file";
1116                 break;
1117         case G_NOPROCORCORE:
1118                 str = "no such process or core file";
1119                 break;
1120         case G_NOEXEC:
1121                 str = "cannot find executable file";
1122                 break;
1123         case G_ZOMB:
1124                 str = "zombie process";
1125                 break;
1126         case G_PERM:
1127                 str = "permission denied";
1128                 break;
1129         case G_BUSY:
1130                 str = "process is traced";
1131                 break;
1132         case G_SYS:
1133                 str = "system process";
1134                 break;
1135         case G_SELF:
1136                 str = "attempt to grab self";
1137                 break;
1138         case G_INTR:
1139                 str = "operation interrupted";
1140                 break;
1141         case G_LP64:
1142                 str = "program is _LP64, self is not";
1143                 break;
1144         case G_FORMAT:
1145                 str = "file is not an ELF core file";
1146                 break;
1147         case G_ELF:
1148                 str = "libelf error";
1149                 break;
1150         case G_NOTE:
1151                 str = "core file is corrupt or missing required data";
1152                 break;
1153         case G_STRANGE:
1154                 str = "unanticipated system error";
1155                 break;
1156         case G_ISAINVAL:
1157                 str = "wrong ELF machine type";
1158                 break;
1159         case G_BADLWPS:
1160                 str = "bad lwp specification";
1161                 break;
1162         case G_NOFD:
1163                 str = "too many open files";
1164                 break;
1165         default:
1166                 str = "unknown error";
1167                 break;
1168         }
1169 
1170         return (str);
1171 }
1172 
1173 /*
1174  * Free a process control structure.
1175  * Close the file descriptors but don't do the Prelease logic.
1176  */
1177 void
1178 Pfree(struct ps_prochandle *P)
1179 {
1180         uint_t i;
1181 
1182         if (P->ucaddrs != NULL) {
1183                 free(P->ucaddrs);
1184                 P->ucaddrs = NULL;
1185                 P->ucnelems = 0;
1186         }
1187 
1188         (void) mutex_lock(&P->proc_lock);
1189         if (P->hashtab != NULL) {
1190                 struct ps_lwphandle *L;
1191                 for (i = 0; i < HASHSIZE; i++) {
1192                         while ((L = P->hashtab[i]) != NULL)
1193                                 Lfree_internal(P, L);
1194                 }
1195                 free(P->hashtab);
1196         }
1197 
1198         while (P->num_fd > 0) {
1199                 fd_info_t *fip = list_next(&P->fd_head);
1200                 list_unlink(fip);
1201                 free(fip);
1202                 P->num_fd--;
1203         }
1204         (void) mutex_unlock(&P->proc_lock);
1205         (void) mutex_destroy(&P->proc_lock);
1206 
1207         if (P->agentctlfd >= 0)
1208                 (void) close(P->agentctlfd);
1209         if (P->agentstatfd >= 0)
1210                 (void) close(P->agentstatfd);
1211         if (P->ctlfd >= 0)
1212                 (void) close(P->ctlfd);
1213         if (P->asfd >= 0)
1214                 (void) close(P->asfd);
1215         if (P->statfd >= 0)
1216                 (void) close(P->statfd);
1217         Preset_maps(P);
1218         P->ops.pop_fini(P, P->data);
1219 
1220         /* clear out the structure as a precaution against reuse */
1221         (void) memset(P, 0, sizeof (*P));
1222         P->ctlfd = -1;
1223         P->asfd = -1;
1224         P->statfd = -1;
1225         P->agentctlfd = -1;
1226         P->agentstatfd = -1;
1227 
1228         free(P);
1229 }
1230 
1231 /*
1232  * Return the state of the process, one of the PS_* values.
1233  */
1234 int
1235 Pstate(struct ps_prochandle *P)
1236 {
1237         return (P->state);
1238 }
1239 
1240 /*
1241  * Return the open address space file descriptor for the process.
1242  * Clients must not close this file descriptor, not use it
1243  * after the process is freed.
1244  */
1245 int
1246 Pasfd(struct ps_prochandle *P)
1247 {
1248         return (P->asfd);
1249 }
1250 
1251 /*
1252  * Return the open control file descriptor for the process.
1253  * Clients must not close this file descriptor, not use it
1254  * after the process is freed.
1255  */
1256 int
1257 Pctlfd(struct ps_prochandle *P)
1258 {
1259         return (P->ctlfd);
1260 }
1261 
1262 /*
1263  * Return a pointer to the process psinfo structure.
1264  * Clients should not hold on to this pointer indefinitely.
1265  * It will become invalid on Prelease().
1266  */
1267 const psinfo_t *
1268 Ppsinfo(struct ps_prochandle *P)
1269 {
1270         return (P->ops.pop_psinfo(P, &P->psinfo, P->data));
1271 }
1272 
1273 /*
1274  * Return a pointer to the process status structure.
1275  * Clients should not hold on to this pointer indefinitely.
1276  * It will become invalid on Prelease().
1277  */
1278 const pstatus_t *
1279 Pstatus(struct ps_prochandle *P)
1280 {
1281         return (&P->status);
1282 }
1283 
1284 static void
1285 Pread_status(struct ps_prochandle *P)
1286 {
1287         P->ops.pop_status(P, &P->status, P->data);
1288 }
1289 
1290 /*
1291  * Fill in a pointer to a process credentials structure.  The ngroups parameter
1292  * is the number of supplementary group entries allocated in the caller's cred
1293  * structure.  It should equal zero or one unless extra space has been
1294  * allocated for the group list by the caller.
1295  */
1296 int
1297 Pcred(struct ps_prochandle *P, prcred_t *pcrp, int ngroups)
1298 {
1299         return (P->ops.pop_cred(P, pcrp, ngroups, P->data));
1300 }
1301 
1302 static prheader_t *
1303 Plstatus(struct ps_prochandle *P)
1304 {
1305         return (P->ops.pop_lstatus(P, P->data));
1306 }
1307 
1308 static prheader_t *
1309 Plpsinfo(struct ps_prochandle *P)
1310 {
1311         return (P->ops.pop_lpsinfo(P, P->data));
1312 }
1313 
1314 
1315 #if defined(__i386) || defined(__amd64)
1316 /*
1317  * Fill in a pointer to a process LDT structure.
1318  * The caller provides a buffer of size 'nldt * sizeof (struct ssd)';
1319  * If pldt == NULL or nldt == 0, we return the number of existing LDT entries.
1320  * Otherwise we return the actual number of LDT entries fetched (<= nldt).
1321  */
1322 int
1323 Pldt(struct ps_prochandle *P, struct ssd *pldt, int nldt)
1324 {
1325         return (P->ops.pop_ldt(P, pldt, nldt, P->data));
1326 
1327 }
1328 #endif  /* __i386 */
1329 
1330 /* ARGSUSED */
1331 void
1332 Ppriv_free(struct ps_prochandle *P, prpriv_t *prv)
1333 {
1334         free(prv);
1335 }
1336 
1337 /*
1338  * Return a malloced process privilege structure in *pprv.
1339  */
1340 int
1341 Ppriv(struct ps_prochandle *P, prpriv_t **pprv)
1342 {
1343         return (P->ops.pop_priv(P, pprv, P->data));
1344 }
1345 
1346 int
1347 Psetpriv(struct ps_prochandle *P, prpriv_t *pprv)
1348 {
1349         int rc;
1350         long *ctl;
1351         size_t sz;
1352 
1353         if (P->state == PS_DEAD) {
1354                 errno = EBADF;
1355                 return (-1);
1356         }
1357 
1358         sz = PRIV_PRPRIV_SIZE(pprv) + sizeof (long);
1359 
1360         sz = ((sz - 1) / sizeof (long) + 1) * sizeof (long);
1361 
1362         ctl = malloc(sz);
1363         if (ctl == NULL)
1364                 return (-1);
1365 
1366         ctl[0] = PCSPRIV;
1367 
1368         (void) memcpy(&ctl[1], pprv, PRIV_PRPRIV_SIZE(pprv));
1369 
1370         if (write(P->ctlfd, ctl, sz) != sz)
1371                 rc = -1;
1372         else
1373                 rc = 0;
1374 
1375         free(ctl);
1376 
1377         return (rc);
1378 }
1379 
1380 void *
1381 Pprivinfo(struct ps_prochandle *P)
1382 {
1383         core_info_t *core = P->data;
1384 
1385         /* Use default from libc */
1386         if (P->state != PS_DEAD)
1387                 return (NULL);
1388 
1389         return (core->core_privinfo);
1390 }
1391 
1392 /*
1393  * Ensure that all cached state is written to the process.
1394  * The cached state is the LWP's signal mask and registers
1395  * and the process's tracing flags.
1396  */
1397 void
1398 Psync(struct ps_prochandle *P)
1399 {
1400         int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
1401         long cmd[6];
1402         iovec_t iov[12];
1403         int n = 0;
1404 
1405         if (P->flags & SETHOLD) {
1406                 cmd[0] = PCSHOLD;
1407                 iov[n].iov_base = (caddr_t)&cmd[0];
1408                 iov[n++].iov_len = sizeof (long);
1409                 iov[n].iov_base = (caddr_t)&P->status.pr_lwp.pr_lwphold;
1410                 iov[n++].iov_len = sizeof (P->status.pr_lwp.pr_lwphold);
1411         }
1412         if (P->flags & SETREGS) {
1413                 cmd[1] = PCSREG;
1414 #ifdef __i386
1415                 /* XX64 we should probably restore REG_GS after this */
1416                 if (ctlfd == P->agentctlfd)
1417                         P->status.pr_lwp.pr_reg[GS] = 0;
1418 #elif defined(__amd64)
1419                 /* XX64 */
1420 #endif
1421                 iov[n].iov_base = (caddr_t)&cmd[1];
1422                 iov[n++].iov_len = sizeof (long);
1423                 iov[n].iov_base = (caddr_t)&P->status.pr_lwp.pr_reg[0];
1424                 iov[n++].iov_len = sizeof (P->status.pr_lwp.pr_reg);
1425         }
1426         if (P->flags & SETSIG) {
1427                 cmd[2] = PCSTRACE;
1428                 iov[n].iov_base = (caddr_t)&cmd[2];
1429                 iov[n++].iov_len = sizeof (long);
1430                 iov[n].iov_base = (caddr_t)&P->status.pr_sigtrace;
1431                 iov[n++].iov_len = sizeof (P->status.pr_sigtrace);
1432         }
1433         if (P->flags & SETFAULT) {
1434                 cmd[3] = PCSFAULT;
1435                 iov[n].iov_base = (caddr_t)&cmd[3];
1436                 iov[n++].iov_len = sizeof (long);
1437                 iov[n].iov_base = (caddr_t)&P->status.pr_flttrace;
1438                 iov[n++].iov_len = sizeof (P->status.pr_flttrace);
1439         }
1440         if (P->flags & SETENTRY) {
1441                 cmd[4] = PCSENTRY;
1442                 iov[n].iov_base = (caddr_t)&cmd[4];
1443                 iov[n++].iov_len = sizeof (long);
1444                 iov[n].iov_base = (caddr_t)&P->status.pr_sysentry;
1445                 iov[n++].iov_len = sizeof (P->status.pr_sysentry);
1446         }
1447         if (P->flags & SETEXIT) {
1448                 cmd[5] = PCSEXIT;
1449                 iov[n].iov_base = (caddr_t)&cmd[5];
1450                 iov[n++].iov_len = sizeof (long);
1451                 iov[n].iov_base = (caddr_t)&P->status.pr_sysexit;
1452                 iov[n++].iov_len = sizeof (P->status.pr_sysexit);
1453         }
1454 
1455         if (n == 0 || writev(ctlfd, iov, n) < 0)
1456                 return;         /* nothing to do or write failed */
1457 
1458         P->flags &= ~(SETSIG|SETFAULT|SETENTRY|SETEXIT|SETHOLD|SETREGS);
1459 }
1460 
1461 /*
1462  * Reopen the /proc file (after PS_LOST).
1463  */
1464 int
1465 Preopen(struct ps_prochandle *P)
1466 {
1467         int fd;
1468         char procname[PATH_MAX];
1469         char *fname;
1470 
1471         if (P->state == PS_DEAD || P->state == PS_IDLE)
1472                 return (0);
1473 
1474         if (P->agentcnt > 0) {
1475                 P->agentcnt = 1;
1476                 Pdestroy_agent(P);
1477         }
1478 
1479         (void) snprintf(procname, sizeof (procname), "%s/%d/",
1480             procfs_path, (int)P->pid);
1481         fname = procname + strlen(procname);
1482 
1483         (void) strcpy(fname, "as");
1484         if ((fd = open(procname, O_RDWR)) < 0 ||
1485             close(P->asfd) < 0 ||
1486             (fd = dupfd(fd, P->asfd)) != P->asfd) {
1487                 dprintf("Preopen: failed to open %s: %s\n",
1488                     procname, strerror(errno));
1489                 if (fd >= 0)
1490                         (void) close(fd);
1491                 return (-1);
1492         }
1493         P->asfd = fd;
1494 
1495         (void) strcpy(fname, "status");
1496         if ((fd = open(procname, O_RDONLY)) < 0 ||
1497             close(P->statfd) < 0 ||
1498             (fd = dupfd(fd, P->statfd)) != P->statfd) {
1499                 dprintf("Preopen: failed to open %s: %s\n",
1500                     procname, strerror(errno));
1501                 if (fd >= 0)
1502                         (void) close(fd);
1503                 return (-1);
1504         }
1505         P->statfd = fd;
1506 
1507         (void) strcpy(fname, "ctl");
1508         if ((fd = open(procname, O_WRONLY)) < 0 ||
1509             close(P->ctlfd) < 0 ||
1510             (fd = dupfd(fd, P->ctlfd)) != P->ctlfd) {
1511                 dprintf("Preopen: failed to open %s: %s\n",
1512                     procname, strerror(errno));
1513                 if (fd >= 0)
1514                         (void) close(fd);
1515                 return (-1);
1516         }
1517         P->ctlfd = fd;
1518 
1519         /*
1520          * Set the state to PS_RUN and wait for the process to stop so that
1521          * we re-read the status from the new P->statfd.  If this fails, Pwait
1522          * will reset the state to PS_LOST and we fail the reopen.  Before
1523          * returning, we also forge a bit of P->status to allow the debugger to
1524          * see that we are PS_LOST following a successful exec.
1525          */
1526         P->state = PS_RUN;
1527         if (Pwait(P, 0) == -1) {
1528 #ifdef _ILP32
1529                 if (errno == EOVERFLOW)
1530                         P->status.pr_dmodel = PR_MODEL_LP64;
1531 #endif
1532                 P->status.pr_lwp.pr_why = PR_SYSEXIT;
1533                 P->status.pr_lwp.pr_what = SYS_execve;
1534                 P->status.pr_lwp.pr_errno = 0;
1535                 return (-1);
1536         }
1537 
1538         /*
1539          * The process should be stopped on exec (REQUESTED)
1540          * or else should be stopped on exit from exec() (SYSEXIT)
1541          */
1542         if (P->state == PS_STOP &&
1543             (P->status.pr_lwp.pr_why == PR_REQUESTED ||
1544             (P->status.pr_lwp.pr_why == PR_SYSEXIT &&
1545             P->status.pr_lwp.pr_what == SYS_execve))) {
1546                 /* fake up stop-on-exit-from-execve */
1547                 if (P->status.pr_lwp.pr_why == PR_REQUESTED) {
1548                         P->status.pr_lwp.pr_why = PR_SYSEXIT;
1549                         P->status.pr_lwp.pr_what = SYS_execve;
1550                         P->status.pr_lwp.pr_errno = 0;
1551                 }
1552         } else {
1553                 dprintf("Preopen: expected REQUESTED or "
1554                     "SYSEXIT(SYS_execve) stop\n");
1555         }
1556 
1557         return (0);
1558 }
1559 
1560 /*
1561  * Define all settable flags other than the microstate accounting flags.
1562  */
1563 #define ALL_SETTABLE_FLAGS (PR_FORK|PR_RLC|PR_KLC|PR_ASYNC|PR_BPTADJ|PR_PTRACE)
1564 
1565 /*
1566  * Restore /proc tracing flags to their original values
1567  * in preparation for releasing the process.
1568  * Also called by Pcreate() to clear all tracing flags.
1569  */
1570 static void
1571 restore_tracing_flags(struct ps_prochandle *P)
1572 {
1573         long flags;
1574         long cmd[4];
1575         iovec_t iov[8];
1576 
1577         if (P->flags & CREATED) {
1578                 /* we created this process; clear all tracing flags */
1579                 premptyset(&P->status.pr_sigtrace);
1580                 premptyset(&P->status.pr_flttrace);
1581                 premptyset(&P->status.pr_sysentry);
1582                 premptyset(&P->status.pr_sysexit);
1583                 if ((P->status.pr_flags & ALL_SETTABLE_FLAGS) != 0)
1584                         (void) Punsetflags(P, ALL_SETTABLE_FLAGS);
1585         } else {
1586                 /* we grabbed the process; restore its tracing flags */
1587                 P->status.pr_sigtrace = P->orig_status.pr_sigtrace;
1588                 P->status.pr_flttrace = P->orig_status.pr_flttrace;
1589                 P->status.pr_sysentry = P->orig_status.pr_sysentry;
1590                 P->status.pr_sysexit  = P->orig_status.pr_sysexit;
1591                 if ((P->status.pr_flags & ALL_SETTABLE_FLAGS) !=
1592                     (flags = (P->orig_status.pr_flags & ALL_SETTABLE_FLAGS))) {
1593                         (void) Punsetflags(P, ALL_SETTABLE_FLAGS);
1594                         if (flags)
1595                                 (void) Psetflags(P, flags);
1596                 }
1597         }
1598 
1599         cmd[0] = PCSTRACE;
1600         iov[0].iov_base = (caddr_t)&cmd[0];
1601         iov[0].iov_len = sizeof (long);
1602         iov[1].iov_base = (caddr_t)&P->status.pr_sigtrace;
1603         iov[1].iov_len = sizeof (P->status.pr_sigtrace);
1604 
1605         cmd[1] = PCSFAULT;
1606         iov[2].iov_base = (caddr_t)&cmd[1];
1607         iov[2].iov_len = sizeof (long);
1608         iov[3].iov_base = (caddr_t)&P->status.pr_flttrace;
1609         iov[3].iov_len = sizeof (P->status.pr_flttrace);
1610 
1611         cmd[2] = PCSENTRY;
1612         iov[4].iov_base = (caddr_t)&cmd[2];
1613         iov[4].iov_len = sizeof (long);
1614         iov[5].iov_base = (caddr_t)&P->status.pr_sysentry;
1615         iov[5].iov_len = sizeof (P->status.pr_sysentry);
1616 
1617         cmd[3] = PCSEXIT;
1618         iov[6].iov_base = (caddr_t)&cmd[3];
1619         iov[6].iov_len = sizeof (long);
1620         iov[7].iov_base = (caddr_t)&P->status.pr_sysexit;
1621         iov[7].iov_len = sizeof (P->status.pr_sysexit);
1622 
1623         (void) writev(P->ctlfd, iov, 8);
1624 
1625         P->flags &= ~(SETSIG|SETFAULT|SETENTRY|SETEXIT);
1626 }
1627 
1628 /*
1629  * Release the process.  Frees the process control structure.
1630  * flags:
1631  *      PRELEASE_CLEAR  Clear all tracing flags.
1632  *      PRELEASE_RETAIN Retain current tracing flags.
1633  *      PRELEASE_HANG   Leave the process stopped and abandoned.
1634  *      PRELEASE_KILL   Terminate the process with SIGKILL.
1635  */
1636 void
1637 Prelease(struct ps_prochandle *P, int flags)
1638 {
1639         if (P->state == PS_DEAD) {
1640                 dprintf("Prelease: releasing handle %p PS_DEAD of pid %d\n",
1641                     (void *)P, (int)P->pid);
1642                 Pfree(P);
1643                 return;
1644         }
1645 
1646         if (P->state == PS_IDLE) {
1647                 file_info_t *fptr = list_next(&P->file_head);
1648                 dprintf("Prelease: releasing handle %p PS_IDLE of file %s\n",
1649                     (void *)P, fptr->file_pname);
1650                 Pfree(P);
1651                 return;
1652         }
1653 
1654         dprintf("Prelease: releasing handle %p pid %d\n",
1655             (void *)P, (int)P->pid);
1656 
1657         if (P->ctlfd == -1) {
1658                 Pfree(P);
1659                 return;
1660         }
1661 
1662         if (P->agentcnt > 0) {
1663                 P->agentcnt = 1;
1664                 Pdestroy_agent(P);
1665         }
1666 
1667         /*
1668          * Attempt to stop the process.
1669          */
1670         P->state = PS_RUN;
1671         (void) Pstop(P, 1000);
1672 
1673         if (flags & PRELEASE_KILL) {
1674                 if (P->state == PS_STOP)
1675                         (void) Psetrun(P, SIGKILL, 0);
1676                 (void) kill(P->pid, SIGKILL);
1677                 Pfree(P);
1678                 return;
1679         }
1680 
1681         /*
1682          * If we lost control, all we can do now is close the files.
1683          * In this case, the last close sets the process running.
1684          */
1685         if (P->state != PS_STOP &&
1686             (P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) == 0) {
1687                 Pfree(P);
1688                 return;
1689         }
1690 
1691         /*
1692          * We didn't lose control; we do more.
1693          */
1694         Psync(P);
1695 
1696         if (flags & PRELEASE_CLEAR)
1697                 P->flags |= CREATED;
1698 
1699         if (!(flags & PRELEASE_RETAIN))
1700                 restore_tracing_flags(P);
1701 
1702         if (flags & PRELEASE_HANG) {
1703                 /* Leave the process stopped and abandoned */
1704                 (void) Punsetflags(P, PR_RLC|PR_KLC);
1705                 Pfree(P);
1706                 return;
1707         }
1708 
1709         /*
1710          * Set the process running if we created it or if it was
1711          * not originally stopped or directed to stop via /proc
1712          * or if we were given the PRELEASE_CLEAR flag.
1713          */
1714         if ((P->flags & CREATED) ||
1715             (P->orig_status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP)) == 0) {
1716                 (void) Psetflags(P, PR_RLC);
1717                 /*
1718                  * We do this repeatedly because the process may have
1719                  * more than one LWP stopped on an event of interest.
1720                  * This makes sure all of them are set running.
1721                  */
1722                 do {
1723                         if (Psetrun(P, 0, 0) == -1 && errno == EBUSY)
1724                                 break; /* Agent LWP may be stuck */
1725                 } while (Pstopstatus(P, PCNULL, 0) == 0 &&
1726                     P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP));
1727 
1728                 if (P->status.pr_lwp.pr_flags & (PR_ISTOP|PR_DSTOP))
1729                         dprintf("Prelease: failed to set process running\n");
1730         }
1731 
1732         Pfree(P);
1733 }
1734 
1735 /* debugging */
1736 void
1737 prldump(const char *caller, lwpstatus_t *lsp)
1738 {
1739         char name[32];
1740         uint32_t bits;
1741 
1742         switch (lsp->pr_why) {
1743         case PR_REQUESTED:
1744                 dprintf("%s: REQUESTED\n", caller);
1745                 break;
1746         case PR_SIGNALLED:
1747                 dprintf("%s: SIGNALLED %s\n", caller,
1748                     proc_signame(lsp->pr_what, name, sizeof (name)));
1749                 break;
1750         case PR_FAULTED:
1751                 dprintf("%s: FAULTED %s\n", caller,
1752                     proc_fltname(lsp->pr_what, name, sizeof (name)));
1753                 break;
1754         case PR_SYSENTRY:
1755                 dprintf("%s: SYSENTRY %s\n", caller,
1756                     proc_sysname(lsp->pr_what, name, sizeof (name)));
1757                 break;
1758         case PR_SYSEXIT:
1759                 dprintf("%s: SYSEXIT %s\n", caller,
1760                     proc_sysname(lsp->pr_what, name, sizeof (name)));
1761                 break;
1762         case PR_JOBCONTROL:
1763                 dprintf("%s: JOBCONTROL %s\n", caller,
1764                     proc_signame(lsp->pr_what, name, sizeof (name)));
1765                 break;
1766         case PR_SUSPENDED:
1767                 dprintf("%s: SUSPENDED\n", caller);
1768                 break;
1769         case PR_BRAND:
1770                 dprintf("%s: BRANDPRIVATE (%d)\n", caller, lsp->pr_what);
1771                 break;
1772         default:
1773                 dprintf("%s: Unknown\n", caller);
1774                 break;
1775         }
1776 
1777         if (lsp->pr_cursig)
1778                 dprintf("%s: p_cursig  = %d\n", caller, lsp->pr_cursig);
1779 
1780         bits = *((uint32_t *)&lsp->pr_lwppend);
1781         if (bits)
1782                 dprintf("%s: pr_lwppend = 0x%.8X\n", caller, bits);
1783 }
1784 
1785 /* debugging */
1786 static void
1787 prdump(struct ps_prochandle *P)
1788 {
1789         uint32_t bits;
1790 
1791         prldump("Pstopstatus", &P->status.pr_lwp);
1792 
1793         bits = *((uint32_t *)&P->status.pr_sigpend);
1794         if (bits)
1795                 dprintf("Pstopstatus: pr_sigpend = 0x%.8X\n", bits);
1796 }
1797 
1798 /*
1799  * Wait for the specified process to stop or terminate.
1800  * Or, just get the current status (PCNULL).
1801  * Or, direct it to stop and get the current status (PCDSTOP).
1802  * If the agent LWP exists, do these things to the agent,
1803  * else do these things to the process as a whole.
1804  */
1805 int
1806 Pstopstatus(struct ps_prochandle *P,
1807         long request,           /* PCNULL, PCDSTOP, PCSTOP, PCWSTOP */
1808         uint_t msec)            /* if non-zero, timeout in milliseconds */
1809 {
1810         int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
1811         long ctl[3];
1812         ssize_t rc;
1813         int err;
1814         int old_state = P->state;
1815 
1816         switch (P->state) {
1817         case PS_RUN:
1818                 break;
1819         case PS_STOP:
1820                 if (request != PCNULL && request != PCDSTOP)
1821                         return (0);
1822                 break;
1823         case PS_LOST:
1824                 if (request != PCNULL) {
1825                         errno = EAGAIN;
1826                         return (-1);
1827                 }
1828                 break;
1829         case PS_UNDEAD:
1830         case PS_DEAD:
1831         case PS_IDLE:
1832                 if (request != PCNULL) {
1833                         errno = ENOENT;
1834                         return (-1);
1835                 }
1836                 break;
1837         default:        /* corrupted state */
1838                 dprintf("Pstopstatus: corrupted state: %d\n", P->state);
1839                 errno = EINVAL;
1840                 return (-1);
1841         }
1842 
1843         ctl[0] = PCDSTOP;
1844         ctl[1] = PCTWSTOP;
1845         ctl[2] = (long)msec;
1846         rc = 0;
1847         switch (request) {
1848         case PCSTOP:
1849                 rc = write(ctlfd, &ctl[0], 3*sizeof (long));
1850                 break;
1851         case PCWSTOP:
1852                 rc = write(ctlfd, &ctl[1], 2*sizeof (long));
1853                 break;
1854         case PCDSTOP:
1855                 rc = write(ctlfd, &ctl[0], 1*sizeof (long));
1856                 break;
1857         case PCNULL:
1858                 if (P->state == PS_DEAD || P->state == PS_IDLE)
1859                         return (0);
1860                 break;
1861         default:        /* programming error */
1862                 errno = EINVAL;
1863                 return (-1);
1864         }
1865         err = (rc < 0)? errno : 0;
1866         Psync(P);
1867 
1868         if (P->agentstatfd < 0) {
1869                 if (pread(P->statfd, &P->status,
1870                     sizeof (P->status), (off_t)0) < 0)
1871                         err = errno;
1872         } else {
1873                 if (pread(P->agentstatfd, &P->status.pr_lwp,
1874                     sizeof (P->status.pr_lwp), (off_t)0) < 0)
1875                         err = errno;
1876                 P->status.pr_flags = P->status.pr_lwp.pr_flags;
1877         }
1878 
1879         if (err) {
1880                 switch (err) {
1881                 case EINTR:             /* user typed ctl-C */
1882                 case ERESTART:
1883                         dprintf("Pstopstatus: EINTR\n");
1884                         break;
1885                 case EAGAIN:            /* we lost control of the the process */
1886                 case EOVERFLOW:
1887                         dprintf("Pstopstatus: PS_LOST, errno=%d\n", err);
1888                         P->state = PS_LOST;
1889                         break;
1890                 default:                /* check for dead process */
1891                         if (_libproc_debug) {
1892                                 const char *errstr;
1893 
1894                                 switch (request) {
1895                                 case PCNULL:
1896                                         errstr = "Pstopstatus PCNULL"; break;
1897                                 case PCSTOP:
1898                                         errstr = "Pstopstatus PCSTOP"; break;
1899                                 case PCDSTOP:
1900                                         errstr = "Pstopstatus PCDSTOP"; break;
1901                                 case PCWSTOP:
1902                                         errstr = "Pstopstatus PCWSTOP"; break;
1903                                 default:
1904                                         errstr = "Pstopstatus PC???"; break;
1905                                 }
1906                                 dprintf("%s: %s\n", errstr, strerror(err));
1907                         }
1908                         deadcheck(P);
1909                         break;
1910                 }
1911                 if (err != EINTR && err != ERESTART) {
1912                         errno = err;
1913                         return (-1);
1914                 }
1915         }
1916 
1917         if (!(P->status.pr_flags & PR_STOPPED)) {
1918                 P->state = PS_RUN;
1919                 if (request == PCNULL || request == PCDSTOP || msec != 0)
1920                         return (0);
1921                 dprintf("Pstopstatus: process is not stopped\n");
1922                 errno = EPROTO;
1923                 return (-1);
1924         }
1925 
1926         P->state = PS_STOP;
1927 
1928         if (_libproc_debug)     /* debugging */
1929                 prdump(P);
1930 
1931         /*
1932          * If the process was already stopped coming into Pstopstatus(),
1933          * then don't use its PC to set P->sysaddr since it may have been
1934          * changed since the time the process originally stopped.
1935          */
1936         if (old_state == PS_STOP)
1937                 return (0);
1938 
1939         switch (P->status.pr_lwp.pr_why) {
1940         case PR_SYSENTRY:
1941         case PR_SYSEXIT:
1942                 if (Pissyscall_prev(P, P->status.pr_lwp.pr_reg[R_PC],
1943                     &P->sysaddr) == 0)
1944                         P->sysaddr = P->status.pr_lwp.pr_reg[R_PC];
1945                 break;
1946         case PR_REQUESTED:
1947         case PR_SIGNALLED:
1948         case PR_FAULTED:
1949         case PR_JOBCONTROL:
1950         case PR_SUSPENDED:
1951         case PR_BRAND:
1952                 break;
1953         default:
1954                 errno = EPROTO;
1955                 return (-1);
1956         }
1957 
1958         return (0);
1959 }
1960 
1961 /*
1962  * Wait for the process to stop for any reason.
1963  */
1964 int
1965 Pwait(struct ps_prochandle *P, uint_t msec)
1966 {
1967         return (Pstopstatus(P, PCWSTOP, msec));
1968 }
1969 
1970 /*
1971  * Direct the process to stop; wait for it to stop.
1972  */
1973 int
1974 Pstop(struct ps_prochandle *P, uint_t msec)
1975 {
1976         return (Pstopstatus(P, PCSTOP, msec));
1977 }
1978 
1979 /*
1980  * Direct the process to stop; don't wait.
1981  */
1982 int
1983 Pdstop(struct ps_prochandle *P)
1984 {
1985         return (Pstopstatus(P, PCDSTOP, 0));
1986 }
1987 
1988 static void
1989 deadcheck(struct ps_prochandle *P)
1990 {
1991         int fd;
1992         void *buf;
1993         size_t size;
1994 
1995         if (P->statfd < 0)
1996                 P->state = PS_UNDEAD;
1997         else {
1998                 if (P->agentstatfd < 0) {
1999                         fd = P->statfd;
2000                         buf = &P->status;
2001                         size = sizeof (P->status);
2002                 } else {
2003                         fd = P->agentstatfd;
2004                         buf = &P->status.pr_lwp;
2005                         size = sizeof (P->status.pr_lwp);
2006                 }
2007                 while (pread(fd, buf, size, (off_t)0) != size) {
2008                         switch (errno) {
2009                         default:
2010                                 P->state = PS_UNDEAD;
2011                                 break;
2012                         case EINTR:
2013                         case ERESTART:
2014                                 continue;
2015                         case EAGAIN:
2016                                 P->state = PS_LOST;
2017                                 break;
2018                         }
2019                         break;
2020                 }
2021                 P->status.pr_flags = P->status.pr_lwp.pr_flags;
2022         }
2023 }
2024 
2025 /*
2026  * Get the value of one register from stopped process.
2027  */
2028 int
2029 Pgetareg(struct ps_prochandle *P, int regno, prgreg_t *preg)
2030 {
2031         if (regno < 0 || regno >= NPRGREG) {
2032                 errno = EINVAL;
2033                 return (-1);
2034         }
2035 
2036         if (P->state == PS_IDLE) {
2037                 errno = ENODATA;
2038                 return (-1);
2039         }
2040 
2041         if (P->state != PS_STOP && P->state != PS_DEAD) {
2042                 errno = EBUSY;
2043                 return (-1);
2044         }
2045 
2046         *preg = P->status.pr_lwp.pr_reg[regno];
2047         return (0);
2048 }
2049 
2050 /*
2051  * Put value of one register into stopped process.
2052  */
2053 int
2054 Pputareg(struct ps_prochandle *P, int regno, prgreg_t reg)
2055 {
2056         if (regno < 0 || regno >= NPRGREG) {
2057                 errno = EINVAL;
2058                 return (-1);
2059         }
2060 
2061         if (P->state != PS_STOP) {
2062                 errno = EBUSY;
2063                 return (-1);
2064         }
2065 
2066         P->status.pr_lwp.pr_reg[regno] = reg;
2067         P->flags |= SETREGS; /* set registers before continuing */
2068         return (0);
2069 }
2070 
2071 int
2072 Psetrun(struct ps_prochandle *P,
2073         int sig,        /* signal to pass to process */
2074         int flags)      /* PRSTEP|PRSABORT|PRSTOP|PRCSIG|PRCFAULT */
2075 {
2076         int ctlfd = (P->agentctlfd >= 0) ? P->agentctlfd : P->ctlfd;
2077         int sbits = (PR_DSTOP | PR_ISTOP | PR_ASLEEP);
2078 
2079         long ctl[1 +                                    /* PCCFAULT     */
2080             1 + sizeof (siginfo_t)/sizeof (long) +      /* PCSSIG/PCCSIG */
2081             2 ];                                        /* PCRUN        */
2082 
2083         long *ctlp = ctl;
2084         size_t size;
2085 
2086         if (P->state != PS_STOP && (P->status.pr_lwp.pr_flags & sbits) == 0) {
2087                 errno = EBUSY;
2088                 return (-1);
2089         }
2090 
2091         Psync(P);       /* flush tracing flags and registers */
2092 
2093         if (flags & PRCFAULT) {             /* clear current fault */
2094                 *ctlp++ = PCCFAULT;
2095                 flags &= ~PRCFAULT;
2096         }
2097 
2098         if (flags & PRCSIG) {               /* clear current signal */
2099                 *ctlp++ = PCCSIG;
2100                 flags &= ~PRCSIG;
2101         } else if (sig && sig != P->status.pr_lwp.pr_cursig) {
2102                 /* make current signal */
2103                 siginfo_t *infop;
2104 
2105                 *ctlp++ = PCSSIG;
2106                 infop = (siginfo_t *)ctlp;
2107                 (void) memset(infop, 0, sizeof (*infop));
2108                 infop->si_signo = sig;
2109                 ctlp += sizeof (siginfo_t) / sizeof (long);
2110         }
2111 
2112         *ctlp++ = PCRUN;
2113         *ctlp++ = flags;
2114         size = (char *)ctlp - (char *)ctl;
2115 
2116         P->info_valid = 0;   /* will need to update map and file info */
2117 
2118         /*
2119          * If we've cached ucontext-list information while we were stopped,
2120          * free it now.
2121          */
2122         if (P->ucaddrs != NULL) {
2123                 free(P->ucaddrs);
2124                 P->ucaddrs = NULL;
2125                 P->ucnelems = 0;
2126         }
2127 
2128         if (write(ctlfd, ctl, size) != size) {
2129                 /* If it is dead or lost, return the real status, not PS_RUN */
2130                 if (errno == ENOENT || errno == EAGAIN) {
2131                         (void) Pstopstatus(P, PCNULL, 0);
2132                         return (0);
2133                 }
2134                 /* If it is not in a jobcontrol stop, issue an error message */
2135                 if (errno != EBUSY ||
2136                     P->status.pr_lwp.pr_why != PR_JOBCONTROL) {
2137                         dprintf("Psetrun: %s\n", strerror(errno));
2138                         return (-1);
2139                 }
2140                 /* Otherwise pretend that the job-stopped process is running */
2141         }
2142 
2143         P->state = PS_RUN;
2144         return (0);
2145 }
2146 
2147 ssize_t
2148 Pread(struct ps_prochandle *P,
2149         void *buf,              /* caller's buffer */
2150         size_t nbyte,           /* number of bytes to read */
2151         uintptr_t address)      /* address in process */
2152 {
2153         return (P->ops.pop_pread(P, buf, nbyte, address, P->data));
2154 }
2155 
2156 ssize_t
2157 Pread_string(struct ps_prochandle *P,
2158         char *buf,              /* caller's buffer */
2159         size_t size,            /* upper limit on bytes to read */
2160         uintptr_t addr)         /* address in process */
2161 {
2162         enum { STRSZ = 40 };
2163         char string[STRSZ + 1];
2164         ssize_t leng = 0;
2165         int nbyte;
2166 
2167         if (size < 2) {
2168                 errno = EINVAL;
2169                 return (-1);
2170         }
2171 
2172         size--;                 /* ensure trailing null fits in buffer */
2173 
2174         *buf = '\0';
2175         string[STRSZ] = '\0';
2176 
2177         for (nbyte = STRSZ; nbyte == STRSZ && leng < size; addr += STRSZ) {
2178                 if ((nbyte = P->ops.pop_pread(P, string, STRSZ, addr,
2179                     P->data)) <= 0) {
2180                         buf[leng] = '\0';
2181                         return (leng ? leng : -1);
2182                 }
2183                 if ((nbyte = strlen(string)) > 0) {
2184                         if (leng + nbyte > size)
2185                                 nbyte = size - leng;
2186                         (void) strncpy(buf + leng, string, nbyte);
2187                         leng += nbyte;
2188                 }
2189         }
2190         buf[leng] = '\0';
2191         return (leng);
2192 }
2193 
2194 ssize_t
2195 Pwrite(struct ps_prochandle *P,
2196         const void *buf,        /* caller's buffer */
2197         size_t nbyte,           /* number of bytes to write */
2198         uintptr_t address)      /* address in process */
2199 {
2200         return (P->ops.pop_pwrite(P, buf, nbyte, address, P->data));
2201 }
2202 
2203 int
2204 Pclearsig(struct ps_prochandle *P)
2205 {
2206         int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2207         long ctl = PCCSIG;
2208 
2209         if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
2210                 return (-1);
2211         P->status.pr_lwp.pr_cursig = 0;
2212         return (0);
2213 }
2214 
2215 int
2216 Pclearfault(struct ps_prochandle *P)
2217 {
2218         int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2219         long ctl = PCCFAULT;
2220 
2221         if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
2222                 return (-1);
2223         return (0);
2224 }
2225 
2226 /*
2227  * Set a breakpoint trap, return original instruction.
2228  */
2229 int
2230 Psetbkpt(struct ps_prochandle *P, uintptr_t address, ulong_t *saved)
2231 {
2232         long ctl[1 + sizeof (priovec_t) / sizeof (long) +       /* PCREAD */
2233             1 + sizeof (priovec_t) / sizeof (long)];    /* PCWRITE */
2234         long *ctlp = ctl;
2235         size_t size;
2236         priovec_t *iovp;
2237         instr_t bpt = BPT;
2238         instr_t old;
2239 
2240         if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2241             P->state == PS_IDLE) {
2242                 errno = ENOENT;
2243                 return (-1);
2244         }
2245 
2246         /* fetch the old instruction */
2247         *ctlp++ = PCREAD;
2248         iovp = (priovec_t *)ctlp;
2249         iovp->pio_base = &old;
2250         iovp->pio_len = sizeof (old);
2251         iovp->pio_offset = address;
2252         ctlp += sizeof (priovec_t) / sizeof (long);
2253 
2254         /* write the BPT instruction */
2255         *ctlp++ = PCWRITE;
2256         iovp = (priovec_t *)ctlp;
2257         iovp->pio_base = &bpt;
2258         iovp->pio_len = sizeof (bpt);
2259         iovp->pio_offset = address;
2260         ctlp += sizeof (priovec_t) / sizeof (long);
2261 
2262         size = (char *)ctlp - (char *)ctl;
2263         if (write(P->ctlfd, ctl, size) != size)
2264                 return (-1);
2265 
2266         /*
2267          * Fail if there was already a breakpoint there from another debugger
2268          * or DTrace's user-level tracing on x86.
2269          */
2270         if (old == BPT) {
2271                 errno = EBUSY;
2272                 return (-1);
2273         }
2274 
2275         *saved = (ulong_t)old;
2276         return (0);
2277 }
2278 
2279 /*
2280  * Restore original instruction where a breakpoint was set.
2281  */
2282 int
2283 Pdelbkpt(struct ps_prochandle *P, uintptr_t address, ulong_t saved)
2284 {
2285         instr_t old = (instr_t)saved;
2286         instr_t cur;
2287 
2288         if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2289             P->state == PS_IDLE) {
2290                 errno = ENOENT;
2291                 return (-1);
2292         }
2293 
2294         /*
2295          * If the breakpoint instruction we had placed has been overwritten
2296          * with a new instruction, then don't try to replace it with the
2297          * old instruction. Doing do can cause problems with self-modifying
2298          * code -- PLTs for example. If the Pread() fails, we assume that we
2299          * should proceed though most likely the Pwrite() will also fail.
2300          */
2301         if (Pread(P, &cur, sizeof (cur), address) == sizeof (cur) &&
2302             cur != BPT)
2303                 return (0);
2304 
2305         if (Pwrite(P, &old, sizeof (old), address) != sizeof (old))
2306                 return (-1);
2307 
2308         return (0);
2309 }
2310 
2311 /*
2312  * Common code for Pxecbkpt() and Lxecbkpt().
2313  * Develop the array of requests that will do the job, then
2314  * write them to the specified control file descriptor.
2315  * Return the non-zero errno if the write fails.
2316  */
2317 static int
2318 execute_bkpt(
2319         int ctlfd,              /* process or LWP control file descriptor */
2320         const fltset_t *faultset,       /* current set of traced faults */
2321         const sigset_t *sigmask,        /* current signal mask */
2322         uintptr_t address,              /* address of breakpint */
2323         ulong_t saved)                  /* the saved instruction */
2324 {
2325         long ctl[
2326             1 + sizeof (sigset_t) / sizeof (long) +             /* PCSHOLD */
2327             1 + sizeof (fltset_t) / sizeof (long) +             /* PCSFAULT */
2328             1 + sizeof (priovec_t) / sizeof (long) +            /* PCWRITE */
2329             2 +                                                 /* PCRUN */
2330             1 +                                                 /* PCWSTOP */
2331             1 +                                                 /* PCCFAULT */
2332             1 + sizeof (priovec_t) / sizeof (long) +            /* PCWRITE */
2333             1 + sizeof (fltset_t) / sizeof (long) +             /* PCSFAULT */
2334             1 + sizeof (sigset_t) / sizeof (long)];             /* PCSHOLD */
2335         long *ctlp = ctl;
2336         sigset_t unblock;
2337         size_t size;
2338         ssize_t ssize;
2339         priovec_t *iovp;
2340         sigset_t *holdp;
2341         fltset_t *faultp;
2342         instr_t old = (instr_t)saved;
2343         instr_t bpt = BPT;
2344         int error = 0;
2345 
2346         /* block our signals for the duration */
2347         (void) sigprocmask(SIG_BLOCK, &blockable_sigs, &unblock);
2348 
2349         /* hold posted signals */
2350         *ctlp++ = PCSHOLD;
2351         holdp = (sigset_t *)ctlp;
2352         prfillset(holdp);
2353         prdelset(holdp, SIGKILL);
2354         prdelset(holdp, SIGSTOP);
2355         ctlp += sizeof (sigset_t) / sizeof (long);
2356 
2357         /* force tracing of FLTTRACE */
2358         if (!(prismember(faultset, FLTTRACE))) {
2359                 *ctlp++ = PCSFAULT;
2360                 faultp = (fltset_t *)ctlp;
2361                 *faultp = *faultset;
2362                 praddset(faultp, FLTTRACE);
2363                 ctlp += sizeof (fltset_t) / sizeof (long);
2364         }
2365 
2366         /* restore the old instruction */
2367         *ctlp++ = PCWRITE;
2368         iovp = (priovec_t *)ctlp;
2369         iovp->pio_base = &old;
2370         iovp->pio_len = sizeof (old);
2371         iovp->pio_offset = address;
2372         ctlp += sizeof (priovec_t) / sizeof (long);
2373 
2374         /* clear current signal and fault; set running w/ single-step */
2375         *ctlp++ = PCRUN;
2376         *ctlp++ = PRCSIG | PRCFAULT | PRSTEP;
2377 
2378         /* wait for stop, cancel the fault */
2379         *ctlp++ = PCWSTOP;
2380         *ctlp++ = PCCFAULT;
2381 
2382         /* restore the breakpoint trap */
2383         *ctlp++ = PCWRITE;
2384         iovp = (priovec_t *)ctlp;
2385         iovp->pio_base = &bpt;
2386         iovp->pio_len = sizeof (bpt);
2387         iovp->pio_offset = address;
2388         ctlp += sizeof (priovec_t) / sizeof (long);
2389 
2390         /* restore fault tracing set */
2391         if (!(prismember(faultset, FLTTRACE))) {
2392                 *ctlp++ = PCSFAULT;
2393                 *(fltset_t *)ctlp = *faultset;
2394                 ctlp += sizeof (fltset_t) / sizeof (long);
2395         }
2396 
2397         /* restore the hold mask */
2398         *ctlp++ = PCSHOLD;
2399         *(sigset_t *)ctlp = *sigmask;
2400         ctlp += sizeof (sigset_t) / sizeof (long);
2401 
2402         size = (char *)ctlp - (char *)ctl;
2403         if ((ssize = write(ctlfd, ctl, size)) != size)
2404                 error = (ssize == -1)? errno : EINTR;
2405         (void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2406         return (error);
2407 }
2408 
2409 /*
2410  * Step over a breakpoint, i.e., execute the instruction that
2411  * really belongs at the breakpoint location (the current %pc)
2412  * and leave the process stopped at the next instruction.
2413  */
2414 int
2415 Pxecbkpt(struct ps_prochandle *P, ulong_t saved)
2416 {
2417         int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2418         int rv, error;
2419 
2420         if (P->state != PS_STOP) {
2421                 errno = EBUSY;
2422                 return (-1);
2423         }
2424 
2425         Psync(P);
2426 
2427         error = execute_bkpt(ctlfd,
2428             &P->status.pr_flttrace, &P->status.pr_lwp.pr_lwphold,
2429             P->status.pr_lwp.pr_reg[R_PC], saved);
2430         rv = Pstopstatus(P, PCNULL, 0);
2431 
2432         if (error != 0) {
2433                 if (P->status.pr_lwp.pr_why == PR_JOBCONTROL &&
2434                     error == EBUSY) {   /* jobcontrol stop -- back off */
2435                         P->state = PS_RUN;
2436                         return (0);
2437                 }
2438                 if (error == ENOENT)
2439                         return (0);
2440                 errno = error;
2441                 return (-1);
2442         }
2443 
2444         return (rv);
2445 }
2446 
2447 /*
2448  * Install the watchpoint described by wp.
2449  */
2450 int
2451 Psetwapt(struct ps_prochandle *P, const prwatch_t *wp)
2452 {
2453         long ctl[1 + sizeof (prwatch_t) / sizeof (long)];
2454         prwatch_t *cwp = (prwatch_t *)&ctl[1];
2455 
2456         if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2457             P->state == PS_IDLE) {
2458                 errno = ENOENT;
2459                 return (-1);
2460         }
2461 
2462         ctl[0] = PCWATCH;
2463         cwp->pr_vaddr = wp->pr_vaddr;
2464         cwp->pr_size = wp->pr_size;
2465         cwp->pr_wflags = wp->pr_wflags;
2466 
2467         if (write(P->ctlfd, ctl, sizeof (ctl)) != sizeof (ctl))
2468                 return (-1);
2469 
2470         return (0);
2471 }
2472 
2473 /*
2474  * Remove the watchpoint described by wp.
2475  */
2476 int
2477 Pdelwapt(struct ps_prochandle *P, const prwatch_t *wp)
2478 {
2479         long ctl[1 + sizeof (prwatch_t) / sizeof (long)];
2480         prwatch_t *cwp = (prwatch_t *)&ctl[1];
2481 
2482         if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2483             P->state == PS_IDLE) {
2484                 errno = ENOENT;
2485                 return (-1);
2486         }
2487 
2488         ctl[0] = PCWATCH;
2489         cwp->pr_vaddr = wp->pr_vaddr;
2490         cwp->pr_size = wp->pr_size;
2491         cwp->pr_wflags = 0;
2492 
2493         if (write(P->ctlfd, ctl, sizeof (ctl)) != sizeof (ctl))
2494                 return (-1);
2495 
2496         return (0);
2497 }
2498 
2499 /*
2500  * Common code for Pxecwapt() and Lxecwapt().  Develop the array of requests
2501  * that will do the job, then write them to the specified control file
2502  * descriptor.  Return the non-zero errno if the write fails.
2503  */
2504 static int
2505 execute_wapt(
2506         int ctlfd,              /* process or LWP control file descriptor */
2507         const fltset_t *faultset,       /* current set of traced faults */
2508         const sigset_t *sigmask,        /* current signal mask */
2509         const prwatch_t *wp)            /* watchpoint descriptor */
2510 {
2511         long ctl[
2512             1 + sizeof (sigset_t) / sizeof (long) +             /* PCSHOLD */
2513             1 + sizeof (fltset_t) / sizeof (long) +             /* PCSFAULT */
2514             1 + sizeof (prwatch_t) / sizeof (long) +            /* PCWATCH */
2515             2 +                                                 /* PCRUN */
2516             1 +                                                 /* PCWSTOP */
2517             1 +                                                 /* PCCFAULT */
2518             1 + sizeof (prwatch_t) / sizeof (long) +            /* PCWATCH */
2519             1 + sizeof (fltset_t) / sizeof (long) +             /* PCSFAULT */
2520             1 + sizeof (sigset_t) / sizeof (long)];             /* PCSHOLD */
2521 
2522         long *ctlp = ctl;
2523         int error = 0;
2524 
2525         sigset_t unblock;
2526         sigset_t *holdp;
2527         fltset_t *faultp;
2528         prwatch_t *prw;
2529         ssize_t ssize;
2530         size_t size;
2531 
2532         (void) sigprocmask(SIG_BLOCK, &blockable_sigs, &unblock);
2533 
2534         /*
2535          * Hold all posted signals in the victim process prior to stepping.
2536          */
2537         *ctlp++ = PCSHOLD;
2538         holdp = (sigset_t *)ctlp;
2539         prfillset(holdp);
2540         prdelset(holdp, SIGKILL);
2541         prdelset(holdp, SIGSTOP);
2542         ctlp += sizeof (sigset_t) / sizeof (long);
2543 
2544         /*
2545          * Force tracing of FLTTRACE since we need to single step.
2546          */
2547         if (!(prismember(faultset, FLTTRACE))) {
2548                 *ctlp++ = PCSFAULT;
2549                 faultp = (fltset_t *)ctlp;
2550                 *faultp = *faultset;
2551                 praddset(faultp, FLTTRACE);
2552                 ctlp += sizeof (fltset_t) / sizeof (long);
2553         }
2554 
2555         /*
2556          * Clear only the current watchpoint by setting pr_wflags to zero.
2557          */
2558         *ctlp++ = PCWATCH;
2559         prw = (prwatch_t *)ctlp;
2560         prw->pr_vaddr = wp->pr_vaddr;
2561         prw->pr_size = wp->pr_size;
2562         prw->pr_wflags = 0;
2563         ctlp += sizeof (prwatch_t) / sizeof (long);
2564 
2565         /*
2566          * Clear the current signal and fault; set running with single-step.
2567          * Then wait for the victim to stop and cancel the FLTTRACE.
2568          */
2569         *ctlp++ = PCRUN;
2570         *ctlp++ = PRCSIG | PRCFAULT | PRSTEP;
2571         *ctlp++ = PCWSTOP;
2572         *ctlp++ = PCCFAULT;
2573 
2574         /*
2575          * Restore the current watchpoint.
2576          */
2577         *ctlp++ = PCWATCH;
2578         (void) memcpy(ctlp, wp, sizeof (prwatch_t));
2579         ctlp += sizeof (prwatch_t) / sizeof (long);
2580 
2581         /*
2582          * Restore fault tracing set if we modified it.
2583          */
2584         if (!(prismember(faultset, FLTTRACE))) {
2585                 *ctlp++ = PCSFAULT;
2586                 *(fltset_t *)ctlp = *faultset;
2587                 ctlp += sizeof (fltset_t) / sizeof (long);
2588         }
2589 
2590         /*
2591          * Restore the hold mask to the current hold mask (i.e. the one
2592          * before we executed any of the previous operations).
2593          */
2594         *ctlp++ = PCSHOLD;
2595         *(sigset_t *)ctlp = *sigmask;
2596         ctlp += sizeof (sigset_t) / sizeof (long);
2597 
2598         size = (char *)ctlp - (char *)ctl;
2599         if ((ssize = write(ctlfd, ctl, size)) != size)
2600                 error = (ssize == -1)? errno : EINTR;
2601         (void) sigprocmask(SIG_SETMASK, &unblock, NULL);
2602         return (error);
2603 }
2604 
2605 /*
2606  * Step over a watchpoint, i.e., execute the instruction that was stopped by
2607  * the watchpoint, and then leave the LWP stopped at the next instruction.
2608  */
2609 int
2610 Pxecwapt(struct ps_prochandle *P, const prwatch_t *wp)
2611 {
2612         int ctlfd = (P->agentctlfd >= 0)? P->agentctlfd : P->ctlfd;
2613         int rv, error;
2614 
2615         if (P->state != PS_STOP) {
2616                 errno = EBUSY;
2617                 return (-1);
2618         }
2619 
2620         Psync(P);
2621         error = execute_wapt(ctlfd,
2622             &P->status.pr_flttrace, &P->status.pr_lwp.pr_lwphold, wp);
2623         rv = Pstopstatus(P, PCNULL, 0);
2624 
2625         if (error != 0) {
2626                 if (P->status.pr_lwp.pr_why == PR_JOBCONTROL &&
2627                     error == EBUSY) {   /* jobcontrol stop -- back off */
2628                         P->state = PS_RUN;
2629                         return (0);
2630                 }
2631                 if (error == ENOENT)
2632                         return (0);
2633                 errno = error;
2634                 return (-1);
2635         }
2636 
2637         return (rv);
2638 }
2639 
2640 int
2641 Psetflags(struct ps_prochandle *P, long flags)
2642 {
2643         int rc;
2644         long ctl[2];
2645 
2646         ctl[0] = PCSET;
2647         ctl[1] = flags;
2648 
2649         if (write(P->ctlfd, ctl, 2*sizeof (long)) != 2*sizeof (long)) {
2650                 rc = -1;
2651         } else {
2652                 P->status.pr_flags |= flags;
2653                 P->status.pr_lwp.pr_flags |= flags;
2654                 rc = 0;
2655         }
2656 
2657         return (rc);
2658 }
2659 
2660 int
2661 Punsetflags(struct ps_prochandle *P, long flags)
2662 {
2663         int rc;
2664         long ctl[2];
2665 
2666         ctl[0] = PCUNSET;
2667         ctl[1] = flags;
2668 
2669         if (write(P->ctlfd, ctl, 2*sizeof (long)) != 2*sizeof (long)) {
2670                 rc = -1;
2671         } else {
2672                 P->status.pr_flags &= ~flags;
2673                 P->status.pr_lwp.pr_flags &= ~flags;
2674                 rc = 0;
2675         }
2676 
2677         return (rc);
2678 }
2679 
2680 /*
2681  * Common function to allow clients to manipulate the action to be taken
2682  * on receipt of a signal, receipt of machine fault, entry to a system call,
2683  * or exit from a system call.  We make use of our private prset_* functions
2684  * in order to make this code be common.  The 'which' parameter identifies
2685  * the code for the event of interest (0 means change the entire set), and
2686  * the 'stop' parameter is a boolean indicating whether the process should
2687  * stop when the event of interest occurs.  The previous value is returned
2688  * to the caller; -1 is returned if an error occurred.
2689  */
2690 static int
2691 Psetaction(struct ps_prochandle *P, void *sp, size_t size,
2692     uint_t flag, int max, int which, int stop)
2693 {
2694         int oldval;
2695 
2696         if (which < 0 || which > max) {
2697                 errno = EINVAL;
2698                 return (-1);
2699         }
2700 
2701         if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2702             P->state == PS_IDLE) {
2703                 errno = ENOENT;
2704                 return (-1);
2705         }
2706 
2707         oldval = prset_ismember(sp, size, which) ? TRUE : FALSE;
2708 
2709         if (stop) {
2710                 if (which == 0) {
2711                         prset_fill(sp, size);
2712                         P->flags |= flag;
2713                 } else if (!oldval) {
2714                         prset_add(sp, size, which);
2715                         P->flags |= flag;
2716                 }
2717         } else {
2718                 if (which == 0) {
2719                         prset_empty(sp, size);
2720                         P->flags |= flag;
2721                 } else if (oldval) {
2722                         prset_del(sp, size, which);
2723                         P->flags |= flag;
2724                 }
2725         }
2726 
2727         if (P->state == PS_RUN)
2728                 Psync(P);
2729 
2730         return (oldval);
2731 }
2732 
2733 /*
2734  * Set action on specified signal.
2735  */
2736 int
2737 Psignal(struct ps_prochandle *P, int which, int stop)
2738 {
2739         int oldval;
2740 
2741         if (which == SIGKILL && stop != 0) {
2742                 errno = EINVAL;
2743                 return (-1);
2744         }
2745 
2746         oldval = Psetaction(P, &P->status.pr_sigtrace, sizeof (sigset_t),
2747             SETSIG, PRMAXSIG, which, stop);
2748 
2749         if (oldval != -1 && which == 0 && stop != 0)
2750                 prdelset(&P->status.pr_sigtrace, SIGKILL);
2751 
2752         return (oldval);
2753 }
2754 
2755 /*
2756  * Set all signal tracing flags.
2757  */
2758 void
2759 Psetsignal(struct ps_prochandle *P, const sigset_t *set)
2760 {
2761         if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2762             P->state == PS_IDLE)
2763                 return;
2764 
2765         P->status.pr_sigtrace = *set;
2766         P->flags |= SETSIG;
2767 
2768         if (P->state == PS_RUN)
2769                 Psync(P);
2770 }
2771 
2772 /*
2773  * Set action on specified fault.
2774  */
2775 int
2776 Pfault(struct ps_prochandle *P, int which, int stop)
2777 {
2778         return (Psetaction(P, &P->status.pr_flttrace, sizeof (fltset_t),
2779             SETFAULT, PRMAXFAULT, which, stop));
2780 }
2781 
2782 /*
2783  * Set all machine fault tracing flags.
2784  */
2785 void
2786 Psetfault(struct ps_prochandle *P, const fltset_t *set)
2787 {
2788         if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2789             P->state == PS_IDLE)
2790                 return;
2791 
2792         P->status.pr_flttrace = *set;
2793         P->flags |= SETFAULT;
2794 
2795         if (P->state == PS_RUN)
2796                 Psync(P);
2797 }
2798 
2799 /*
2800  * Set action on specified system call entry.
2801  */
2802 int
2803 Psysentry(struct ps_prochandle *P, int which, int stop)
2804 {
2805         return (Psetaction(P, &P->status.pr_sysentry, sizeof (sysset_t),
2806             SETENTRY, PRMAXSYS, which, stop));
2807 }
2808 
2809 /*
2810  * Set all system call entry tracing flags.
2811  */
2812 void
2813 Psetsysentry(struct ps_prochandle *P, const sysset_t *set)
2814 {
2815         if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2816             P->state == PS_IDLE)
2817                 return;
2818 
2819         P->status.pr_sysentry = *set;
2820         P->flags |= SETENTRY;
2821 
2822         if (P->state == PS_RUN)
2823                 Psync(P);
2824 }
2825 
2826 /*
2827  * Set action on specified system call exit.
2828  */
2829 int
2830 Psysexit(struct ps_prochandle *P, int which, int stop)
2831 {
2832         return (Psetaction(P, &P->status.pr_sysexit, sizeof (sysset_t),
2833             SETEXIT, PRMAXSYS, which, stop));
2834 }
2835 
2836 /*
2837  * Set all system call exit tracing flags.
2838  */
2839 void
2840 Psetsysexit(struct ps_prochandle *P, const sysset_t *set)
2841 {
2842         if (P->state == PS_DEAD || P->state == PS_UNDEAD ||
2843             P->state == PS_IDLE)
2844                 return;
2845 
2846         P->status.pr_sysexit = *set;
2847         P->flags |= SETEXIT;
2848 
2849         if (P->state == PS_RUN)
2850                 Psync(P);
2851 }
2852 
2853 /*
2854  * Utility function to read the contents of a file that contains a
2855  * prheader_t at the start (/proc/pid/lstatus or /proc/pid/lpsinfo).
2856  * Returns a malloc()d buffer or NULL on failure.
2857  */
2858 static prheader_t *
2859 read_lfile(struct ps_prochandle *P, const char *lname)
2860 {
2861         prheader_t *Lhp;
2862         char lpath[PATH_MAX];
2863         struct stat64 statb;
2864         int fd;
2865         size_t size;
2866         ssize_t rval;
2867 
2868         (void) snprintf(lpath, sizeof (lpath), "%s/%d/%s", procfs_path,
2869             (int)P->status.pr_pid, lname);
2870         if ((fd = open(lpath, O_RDONLY)) < 0 || fstat64(fd, &statb) != 0) {
2871                 if (fd >= 0)
2872                         (void) close(fd);
2873                 return (NULL);
2874         }
2875 
2876         /*
2877          * 'size' is just the initial guess at the buffer size.
2878          * It will have to grow if the number of lwps increases
2879          * while we are looking at the process.
2880          * 'size' must be larger than the actual file size.
2881          */
2882         size = statb.st_size + 32;
2883 
2884         for (;;) {
2885                 if ((Lhp = malloc(size)) == NULL)
2886                         break;
2887                 if ((rval = pread(fd, Lhp, size, 0)) < 0 ||
2888                     rval <= sizeof (prheader_t)) {
2889                         free(Lhp);
2890                         Lhp = NULL;
2891                         break;
2892                 }
2893                 if (rval < size)
2894                         break;
2895                 /* need a bigger buffer */
2896                 free(Lhp);
2897                 size *= 2;
2898         }
2899 
2900         (void) close(fd);
2901         return (Lhp);
2902 }
2903 
2904 /*
2905  * LWP iteration interface.
2906  */
2907 int
2908 Plwp_iter(struct ps_prochandle *P, proc_lwp_f *func, void *cd)
2909 {
2910         prheader_t *Lhp;
2911         lwpstatus_t *Lsp;
2912         long nlwp;
2913         int rv;
2914 
2915         switch (P->state) {
2916         case PS_RUN:
2917                 (void) Pstopstatus(P, PCNULL, 0);
2918                 break;
2919 
2920         case PS_STOP:
2921                 Psync(P);
2922                 break;
2923 
2924         case PS_IDLE:
2925                 errno = ENODATA;
2926                 return (-1);
2927         }
2928 
2929         /*
2930          * For either live processes or cores, the single LWP case is easy:
2931          * the pstatus_t contains the lwpstatus_t for the only LWP.
2932          */
2933         if (P->status.pr_nlwp <= 1)
2934                 return (func(cd, &P->status.pr_lwp));
2935 
2936         /*
2937          * For the core file multi-LWP case, we just iterate through the
2938          * list of LWP structs we read in from the core file.
2939          */
2940         if (P->state == PS_DEAD) {
2941                 core_info_t *core = P->data;
2942                 lwp_info_t *lwp = list_prev(&core->core_lwp_head);
2943                 uint_t i;
2944 
2945                 for (i = 0; i < core->core_nlwp; i++, lwp = list_prev(lwp)) {
2946                         if (lwp->lwp_psinfo.pr_sname != 'Z' &&
2947                             (rv = func(cd, &lwp->lwp_status)) != 0)
2948                                 break;
2949                 }
2950 
2951                 return (rv);
2952         }
2953 
2954         /*
2955          * For the live process multi-LWP case, we have to work a little
2956          * harder: the /proc/pid/lstatus file has the array of LWP structs.
2957          */
2958         if ((Lhp = Plstatus(P)) == NULL)
2959                 return (-1);
2960 
2961         for (nlwp = Lhp->pr_nent, Lsp = (lwpstatus_t *)(uintptr_t)(Lhp + 1);
2962             nlwp > 0;
2963             nlwp--, Lsp = (lwpstatus_t *)((uintptr_t)Lsp + Lhp->pr_entsize)) {
2964                 if ((rv = func(cd, Lsp)) != 0)
2965                         break;
2966         }
2967 
2968         free(Lhp);
2969         return (rv);
2970 }
2971 
2972 /*
2973  * Extended LWP iteration interface.
2974  * Iterate over all LWPs, active and zombie.
2975  */
2976 int
2977 Plwp_iter_all(struct ps_prochandle *P, proc_lwp_all_f *func, void *cd)
2978 {
2979         prheader_t *Lhp = NULL;
2980         lwpstatus_t *Lsp;
2981         lwpstatus_t *sp;
2982         prheader_t *Lphp = NULL;
2983         lwpsinfo_t *Lpsp;
2984         long nstat;
2985         long ninfo;
2986         int rv;
2987 
2988 retry:
2989         if (Lhp != NULL)
2990                 free(Lhp);
2991         if (Lphp != NULL)
2992                 free(Lphp);
2993         if (P->state == PS_RUN)
2994                 (void) Pstopstatus(P, PCNULL, 0);
2995         (void) Ppsinfo(P);
2996 
2997         if (P->state == PS_STOP)
2998                 Psync(P);
2999 
3000         /*
3001          * For either live processes or cores, the single LWP case is easy:
3002          * the pstatus_t contains the lwpstatus_t for the only LWP and
3003          * the psinfo_t contains the lwpsinfo_t for the only LWP.
3004          */
3005         if (P->status.pr_nlwp + P->status.pr_nzomb <= 1)
3006                 return (func(cd, &P->status.pr_lwp, &P->psinfo.pr_lwp));
3007 
3008         /*
3009          * For the core file multi-LWP case, we just iterate through the
3010          * list of LWP structs we read in from the core file.
3011          */
3012         if (P->state == PS_DEAD) {
3013                 core_info_t *core = P->data;
3014                 lwp_info_t *lwp = list_prev(&core->core_lwp_head);
3015                 uint_t i;
3016 
3017                 for (i = 0; i < core->core_nlwp; i++, lwp = list_prev(lwp)) {
3018                         sp = (lwp->lwp_psinfo.pr_sname == 'Z')? NULL :
3019                             &lwp->lwp_status;
3020                         if ((rv = func(cd, sp, &lwp->lwp_psinfo)) != 0)
3021                                 break;
3022                 }
3023 
3024                 return (rv);
3025         }
3026 
3027         /*
3028          * For all other cases retrieve the array of lwpstatus_t's and
3029          * lwpsinfo_t's.
3030          */
3031         if ((Lhp = Plstatus(P)) == NULL)
3032                 return (-1);
3033         if ((Lphp = Plpsinfo(P)) == NULL) {
3034                 free(Lhp);
3035                 return (-1);
3036         }
3037 
3038         /*
3039          * If we are looking at a running process, or one we do not control,
3040          * the active and zombie lwps in the process may have changed since
3041          * we read the process status structure.  If so, just start over.
3042          */
3043         if (Lhp->pr_nent != P->status.pr_nlwp ||
3044             Lphp->pr_nent != P->status.pr_nlwp + P->status.pr_nzomb)
3045                 goto retry;
3046 
3047         /*
3048          * To be perfectly safe, prescan the two arrays, checking consistency.
3049          * We rely on /proc giving us lwpstatus_t's and lwpsinfo_t's in the
3050          * same order (the lwp directory order) in their respective files.
3051          * We also rely on there being (possibly) more lwpsinfo_t's than
3052          * lwpstatus_t's (the extra lwpsinfo_t's are for zombie lwps).
3053          */
3054         Lsp = (lwpstatus_t *)(uintptr_t)(Lhp + 1);
3055         Lpsp = (lwpsinfo_t *)(uintptr_t)(Lphp + 1);
3056         nstat = Lhp->pr_nent;
3057         for (ninfo = Lphp->pr_nent; ninfo != 0; ninfo--) {
3058                 if (Lpsp->pr_sname != 'Z') {
3059                         /*
3060                          * Not a zombie lwp; check for matching lwpids.
3061                          */
3062                         if (nstat == 0 || Lsp->pr_lwpid != Lpsp->pr_lwpid)
3063                                 goto retry;
3064                         Lsp = (lwpstatus_t *)((uintptr_t)Lsp + Lhp->pr_entsize);
3065                         nstat--;
3066                 }
3067                 Lpsp = (lwpsinfo_t *)((uintptr_t)Lpsp + Lphp->pr_entsize);
3068         }
3069         if (nstat != 0)
3070                 goto retry;
3071 
3072         /*
3073          * Rescan, this time for real.
3074          */
3075         Lsp = (lwpstatus_t *)(uintptr_t)(Lhp + 1);
3076         Lpsp = (lwpsinfo_t *)(uintptr_t)(Lphp + 1);
3077         for (ninfo = Lphp->pr_nent; ninfo != 0; ninfo--) {
3078                 if (Lpsp->pr_sname != 'Z') {
3079                         sp = Lsp;
3080                         Lsp = (lwpstatus_t *)((uintptr_t)Lsp + Lhp->pr_entsize);
3081                 } else {
3082                         sp = NULL;
3083                 }
3084                 if ((rv = func(cd, sp, Lpsp)) != 0)
3085                         break;
3086                 Lpsp = (lwpsinfo_t *)((uintptr_t)Lpsp + Lphp->pr_entsize);
3087         }
3088 
3089         free(Lhp);
3090         free(Lphp);
3091         return (rv);
3092 }
3093 
3094 core_content_t
3095 Pcontent(struct ps_prochandle *P)
3096 {
3097         core_info_t *core = P->data;
3098 
3099         if (P->state == PS_DEAD)
3100                 return (core->core_content);
3101         if (P->state == PS_IDLE)
3102                 return (CC_CONTENT_TEXT | CC_CONTENT_DATA | CC_CONTENT_CTF);
3103 
3104         return (CC_CONTENT_ALL);
3105 }
3106 
3107 /*
3108  * =================================================================
3109  * The remainder of the functions in this file are for the
3110  * control of individual LWPs in the controlled process.
3111  * =================================================================
3112  */
3113 
3114 /*
3115  * Find an entry in the process hash table for the specified lwpid.
3116  * The entry will either point to an existing struct ps_lwphandle
3117  * or it will point to an empty slot for a new struct ps_lwphandle.
3118  */
3119 static struct ps_lwphandle **
3120 Lfind(struct ps_prochandle *P, lwpid_t lwpid)
3121 {
3122         struct ps_lwphandle **Lp;
3123         struct ps_lwphandle *L;
3124 
3125         for (Lp = &P->hashtab[lwpid % (HASHSIZE - 1)];
3126             (L = *Lp) != NULL; Lp = &L->lwp_hash)
3127                 if (L->lwp_id == lwpid)
3128                         break;
3129         return (Lp);
3130 }
3131 
3132 /*
3133  * Grab an LWP contained within the controlled process.
3134  * Return an opaque pointer to its LWP control structure.
3135  *      perr: pointer to error return code.
3136  */
3137 struct ps_lwphandle *
3138 Lgrab(struct ps_prochandle *P, lwpid_t lwpid, int *perr)
3139 {
3140         struct ps_lwphandle **Lp;
3141         struct ps_lwphandle *L;
3142         int fd;
3143         char procname[PATH_MAX];
3144         char *fname;
3145         int rc = 0;
3146 
3147         (void) mutex_lock(&P->proc_lock);
3148 
3149         if (P->state == PS_UNDEAD || P->state == PS_IDLE)
3150                 rc = G_NOPROC;
3151         else if (P->hashtab == NULL &&
3152             (P->hashtab = calloc(HASHSIZE, sizeof (struct ps_lwphandle *)))
3153             == NULL)
3154                 rc = G_STRANGE;
3155         else if (*(Lp = Lfind(P, lwpid)) != NULL)
3156                 rc = G_BUSY;
3157         else if ((L = malloc(sizeof (struct ps_lwphandle))) == NULL)
3158                 rc = G_STRANGE;
3159         if (rc) {
3160                 *perr = rc;
3161                 (void) mutex_unlock(&P->proc_lock);
3162                 return (NULL);
3163         }
3164 
3165         (void) memset(L, 0, sizeof (*L));
3166         L->lwp_ctlfd = -1;
3167         L->lwp_statfd = -1;
3168         L->lwp_proc = P;
3169         L->lwp_id = lwpid;
3170         *Lp = L;        /* insert into the hash table */
3171 
3172         if (P->state == PS_DEAD) {   /* core file */
3173                 if (getlwpstatus(P, lwpid, &L->lwp_status) == -1) {
3174                         rc = G_NOPROC;
3175                         goto err;
3176                 }
3177                 L->lwp_state = PS_DEAD;
3178                 *perr = 0;
3179                 (void) mutex_unlock(&P->proc_lock);
3180                 return (L);
3181         }
3182 
3183         /*
3184          * Open the /proc/<pid>/lwp/<lwpid> files
3185          */
3186         (void) snprintf(procname, sizeof (procname), "%s/%d/lwp/%d/",
3187             procfs_path, (int)P->pid, (int)lwpid);
3188         fname = procname + strlen(procname);
3189         (void) set_minfd();
3190 
3191         (void) strcpy(fname, "lwpstatus");
3192         if ((fd = open(procname, O_RDONLY)) < 0 ||
3193             (fd = dupfd(fd, 0)) < 0) {
3194                 switch (errno) {
3195                 case ENOENT:
3196                         rc = G_NOPROC;
3197                         break;
3198                 default:
3199                         dprintf("Lgrab: failed to open %s: %s\n",
3200                             procname, strerror(errno));
3201                         rc = G_STRANGE;
3202                         break;
3203                 }
3204                 goto err;
3205         }
3206         L->lwp_statfd = fd;
3207 
3208         if (pread(fd, &L->lwp_status, sizeof (L->lwp_status), (off_t)0) < 0) {
3209                 switch (errno) {
3210                 case ENOENT:
3211                         rc = G_NOPROC;
3212                         break;
3213                 default:
3214                         dprintf("Lgrab: failed to read %s: %s\n",
3215                             procname, strerror(errno));
3216                         rc = G_STRANGE;
3217                         break;
3218                 }
3219                 goto err;
3220         }
3221 
3222         (void) strcpy(fname, "lwpctl");
3223         if ((fd = open(procname, O_WRONLY)) < 0 ||
3224             (fd = dupfd(fd, 0)) < 0) {
3225                 switch (errno) {
3226                 case ENOENT:
3227                         rc = G_NOPROC;
3228                         break;
3229                 default:
3230                         dprintf("Lgrab: failed to open %s: %s\n",
3231                             procname, strerror(errno));
3232                         rc = G_STRANGE;
3233                         break;
3234                 }
3235                 goto err;
3236         }
3237         L->lwp_ctlfd = fd;
3238 
3239         L->lwp_state =
3240             ((L->lwp_status.pr_flags & (PR_STOPPED|PR_ISTOP))
3241             == (PR_STOPPED|PR_ISTOP))?
3242             PS_STOP : PS_RUN;
3243 
3244         *perr = 0;
3245         (void) mutex_unlock(&P->proc_lock);
3246         return (L);
3247 
3248 err:
3249         Lfree_internal(P, L);
3250         *perr = rc;
3251         (void) mutex_unlock(&P->proc_lock);
3252         return (NULL);
3253 }
3254 
3255 /*
3256  * Return a printable string corresponding to an Lgrab() error return.
3257  */
3258 const char *
3259 Lgrab_error(int error)
3260 {
3261         const char *str;
3262 
3263         switch (error) {
3264         case G_NOPROC:
3265                 str = "no such LWP";
3266                 break;
3267         case G_BUSY:
3268                 str = "LWP already grabbed";
3269                 break;
3270         case G_STRANGE:
3271                 str = "unanticipated system error";
3272                 break;
3273         default:
3274                 str = "unknown error";
3275                 break;
3276         }
3277 
3278         return (str);
3279 }
3280 
3281 /*
3282  * Free an LWP control structure.
3283  */
3284 void
3285 Lfree(struct ps_lwphandle *L)
3286 {
3287         struct ps_prochandle *P = L->lwp_proc;
3288 
3289         (void) mutex_lock(&P->proc_lock);
3290         Lfree_internal(P, L);
3291         (void) mutex_unlock(&P->proc_lock);
3292 }
3293 
3294 static void
3295 Lfree_internal(struct ps_prochandle *P, struct ps_lwphandle *L)
3296 {
3297         *Lfind(P, L->lwp_id) = L->lwp_hash;       /* delete from hash table */
3298         if (L->lwp_ctlfd >= 0)
3299                 (void) close(L->lwp_ctlfd);
3300         if (L->lwp_statfd >= 0)
3301                 (void) close(L->lwp_statfd);
3302 
3303         /* clear out the structure as a precaution against reuse */
3304         (void) memset(L, 0, sizeof (*L));
3305         L->lwp_ctlfd = -1;
3306         L->lwp_statfd = -1;
3307 
3308         free(L);
3309 }
3310 
3311 /*
3312  * Return the state of the process, one of the PS_* values.
3313  */
3314 int
3315 Lstate(struct ps_lwphandle *L)
3316 {
3317         return (L->lwp_state);
3318 }
3319 
3320 /*
3321  * Return the open control file descriptor for the LWP.
3322  * Clients must not close this file descriptor, nor use it
3323  * after the LWP is freed.
3324  */
3325 int
3326 Lctlfd(struct ps_lwphandle *L)
3327 {
3328         return (L->lwp_ctlfd);
3329 }
3330 
3331 /*
3332  * Return a pointer to the LWP lwpsinfo structure.
3333  * Clients should not hold on to this pointer indefinitely.
3334  * It will become invalid on Lfree().
3335  */
3336 const lwpsinfo_t *
3337 Lpsinfo(struct ps_lwphandle *L)
3338 {
3339         if (Plwp_getpsinfo(L->lwp_proc, L->lwp_id, &L->lwp_psinfo) == -1)
3340                 return (NULL);
3341 
3342         return (&L->lwp_psinfo);
3343 }
3344 
3345 /*
3346  * Return a pointer to the LWP status structure.
3347  * Clients should not hold on to this pointer indefinitely.
3348  * It will become invalid on Lfree().
3349  */
3350 const lwpstatus_t *
3351 Lstatus(struct ps_lwphandle *L)
3352 {
3353         return (&L->lwp_status);
3354 }
3355 
3356 /*
3357  * Given an LWP handle, return the process handle.
3358  */
3359 struct ps_prochandle *
3360 Lprochandle(struct ps_lwphandle *L)
3361 {
3362         return (L->lwp_proc);
3363 }
3364 
3365 /*
3366  * Ensure that all cached state is written to the LWP.
3367  * The cached state is the LWP's signal mask and registers.
3368  */
3369 void
3370 Lsync(struct ps_lwphandle *L)
3371 {
3372         int ctlfd = L->lwp_ctlfd;
3373         long cmd[2];
3374         iovec_t iov[4];
3375         int n = 0;
3376 
3377         if (L->lwp_flags & SETHOLD) {
3378                 cmd[0] = PCSHOLD;
3379                 iov[n].iov_base = (caddr_t)&cmd[0];
3380                 iov[n++].iov_len = sizeof (long);
3381                 iov[n].iov_base = (caddr_t)&L->lwp_status.pr_lwphold;
3382                 iov[n++].iov_len = sizeof (L->lwp_status.pr_lwphold);
3383         }
3384         if (L->lwp_flags & SETREGS) {
3385                 cmd[1] = PCSREG;
3386                 iov[n].iov_base = (caddr_t)&cmd[1];
3387                 iov[n++].iov_len = sizeof (long);
3388                 iov[n].iov_base = (caddr_t)&L->lwp_status.pr_reg[0];
3389                 iov[n++].iov_len = sizeof (L->lwp_status.pr_reg);
3390         }
3391 
3392         if (n == 0 || writev(ctlfd, iov, n) < 0)
3393                 return;         /* nothing to do or write failed */
3394 
3395         L->lwp_flags &= ~(SETHOLD|SETREGS);
3396 }
3397 
3398 /*
3399  * Wait for the specified LWP to stop or terminate.
3400  * Or, just get the current status (PCNULL).
3401  * Or, direct it to stop and get the current status (PCDSTOP).
3402  */
3403 static int
3404 Lstopstatus(struct ps_lwphandle *L,
3405         long request,           /* PCNULL, PCDSTOP, PCSTOP, PCWSTOP */
3406         uint_t msec)            /* if non-zero, timeout in milliseconds */
3407 {
3408         int ctlfd = L->lwp_ctlfd;
3409         long ctl[3];
3410         ssize_t rc;
3411         int err;
3412 
3413         switch (L->lwp_state) {
3414         case PS_RUN:
3415                 break;
3416         case PS_STOP:
3417                 if (request != PCNULL && request != PCDSTOP)
3418                         return (0);
3419                 break;
3420         case PS_LOST:
3421                 if (request != PCNULL) {
3422                         errno = EAGAIN;
3423                         return (-1);
3424                 }
3425                 break;
3426         case PS_UNDEAD:
3427         case PS_DEAD:
3428                 if (request != PCNULL) {
3429                         errno = ENOENT;
3430                         return (-1);
3431                 }
3432                 break;
3433         default:        /* corrupted state */
3434                 dprintf("Lstopstatus: corrupted state: %d\n", L->lwp_state);
3435                 errno = EINVAL;
3436                 return (-1);
3437         }
3438 
3439         ctl[0] = PCDSTOP;
3440         ctl[1] = PCTWSTOP;
3441         ctl[2] = (long)msec;
3442         rc = 0;
3443         switch (request) {
3444         case PCSTOP:
3445                 rc = write(ctlfd, &ctl[0], 3*sizeof (long));
3446                 break;
3447         case PCWSTOP:
3448                 rc = write(ctlfd, &ctl[1], 2*sizeof (long));
3449                 break;
3450         case PCDSTOP:
3451                 rc = write(ctlfd, &ctl[0], 1*sizeof (long));
3452                 break;
3453         case PCNULL:
3454                 if (L->lwp_state == PS_DEAD)
3455                         return (0); /* Nothing else to do for cores */
3456                 break;
3457         default:        /* programming error */
3458                 errno = EINVAL;
3459                 return (-1);
3460         }
3461         err = (rc < 0)? errno : 0;
3462         Lsync(L);
3463 
3464         if (pread(L->lwp_statfd, &L->lwp_status,
3465             sizeof (L->lwp_status), (off_t)0) < 0)
3466                 err = errno;
3467 
3468         if (err) {
3469                 switch (err) {
3470                 case EINTR:             /* user typed ctl-C */
3471                 case ERESTART:
3472                         dprintf("Lstopstatus: EINTR\n");
3473                         break;
3474                 case EAGAIN:            /* we lost control of the the process */
3475                         dprintf("Lstopstatus: EAGAIN\n");
3476                         L->lwp_state = PS_LOST;
3477                         errno = err;
3478                         return (-1);
3479                 default:
3480                         if (_libproc_debug) {
3481                                 const char *errstr;
3482 
3483                                 switch (request) {
3484                                 case PCNULL:
3485                                         errstr = "Lstopstatus PCNULL"; break;
3486                                 case PCSTOP:
3487                                         errstr = "Lstopstatus PCSTOP"; break;
3488                                 case PCDSTOP:
3489                                         errstr = "Lstopstatus PCDSTOP"; break;
3490                                 case PCWSTOP:
3491                                         errstr = "Lstopstatus PCWSTOP"; break;
3492                                 default:
3493                                         errstr = "Lstopstatus PC???"; break;
3494                                 }
3495                                 dprintf("%s: %s\n", errstr, strerror(err));
3496                         }
3497                         L->lwp_state = PS_UNDEAD;
3498                         errno = err;
3499                         return (-1);
3500                 }
3501         }
3502 
3503         if ((L->lwp_status.pr_flags & (PR_STOPPED|PR_ISTOP))
3504             != (PR_STOPPED|PR_ISTOP)) {
3505                 L->lwp_state = PS_RUN;
3506                 if (request == PCNULL || request == PCDSTOP || msec != 0)
3507                         return (0);
3508                 dprintf("Lstopstatus: LWP is not stopped\n");
3509                 errno = EPROTO;
3510                 return (-1);
3511         }
3512 
3513         L->lwp_state = PS_STOP;
3514 
3515         if (_libproc_debug)     /* debugging */
3516                 prldump("Lstopstatus", &L->lwp_status);
3517 
3518         switch (L->lwp_status.pr_why) {
3519         case PR_SYSENTRY:
3520         case PR_SYSEXIT:
3521         case PR_REQUESTED:
3522         case PR_SIGNALLED:
3523         case PR_FAULTED:
3524         case PR_JOBCONTROL:
3525         case PR_SUSPENDED:
3526         case PR_BRAND:
3527                 break;
3528         default:
3529                 errno = EPROTO;
3530                 return (-1);
3531         }
3532 
3533         return (0);
3534 }
3535 
3536 /*
3537  * Wait for the LWP to stop for any reason.
3538  */
3539 int
3540 Lwait(struct ps_lwphandle *L, uint_t msec)
3541 {
3542         return (Lstopstatus(L, PCWSTOP, msec));
3543 }
3544 
3545 /*
3546  * Direct the LWP to stop; wait for it to stop.
3547  */
3548 int
3549 Lstop(struct ps_lwphandle *L, uint_t msec)
3550 {
3551         return (Lstopstatus(L, PCSTOP, msec));
3552 }
3553 
3554 /*
3555  * Direct the LWP to stop; don't wait.
3556  */
3557 int
3558 Ldstop(struct ps_lwphandle *L)
3559 {
3560         return (Lstopstatus(L, PCDSTOP, 0));
3561 }
3562 
3563 /*
3564  * Get the value of one register from stopped LWP.
3565  */
3566 int
3567 Lgetareg(struct ps_lwphandle *L, int regno, prgreg_t *preg)
3568 {
3569         if (regno < 0 || regno >= NPRGREG) {
3570                 errno = EINVAL;
3571                 return (-1);
3572         }
3573 
3574         if (L->lwp_state != PS_STOP) {
3575                 errno = EBUSY;
3576                 return (-1);
3577         }
3578 
3579         *preg = L->lwp_status.pr_reg[regno];
3580         return (0);
3581 }
3582 
3583 /*
3584  * Put value of one register into stopped LWP.
3585  */
3586 int
3587 Lputareg(struct ps_lwphandle *L, int regno, prgreg_t reg)
3588 {
3589         if (regno < 0 || regno >= NPRGREG) {
3590                 errno = EINVAL;
3591                 return (-1);
3592         }
3593 
3594         if (L->lwp_state != PS_STOP) {
3595                 errno = EBUSY;
3596                 return (-1);
3597         }
3598 
3599         L->lwp_status.pr_reg[regno] = reg;
3600         L->lwp_flags |= SETREGS;     /* set registers before continuing */
3601         return (0);
3602 }
3603 
3604 int
3605 Lsetrun(struct ps_lwphandle *L,
3606         int sig,        /* signal to pass to LWP */
3607         int flags)      /* PRSTEP|PRSABORT|PRSTOP|PRCSIG|PRCFAULT */
3608 {
3609         int ctlfd = L->lwp_ctlfd;
3610         int sbits = (PR_DSTOP | PR_ISTOP | PR_ASLEEP);
3611 
3612         long ctl[1 +                                    /* PCCFAULT     */
3613             1 + sizeof (siginfo_t)/sizeof (long) +      /* PCSSIG/PCCSIG */
3614             2 ];                                        /* PCRUN        */
3615 
3616         long *ctlp = ctl;
3617         size_t size;
3618 
3619         if (L->lwp_state != PS_STOP &&
3620             (L->lwp_status.pr_flags & sbits) == 0) {
3621                 errno = EBUSY;
3622                 return (-1);
3623         }
3624 
3625         Lsync(L);       /* flush registers */
3626 
3627         if (flags & PRCFAULT) {             /* clear current fault */
3628                 *ctlp++ = PCCFAULT;
3629                 flags &= ~PRCFAULT;
3630         }
3631 
3632         if (flags & PRCSIG) {               /* clear current signal */
3633                 *ctlp++ = PCCSIG;
3634                 flags &= ~PRCSIG;
3635         } else if (sig && sig != L->lwp_status.pr_cursig) {
3636                 /* make current signal */
3637                 siginfo_t *infop;
3638 
3639                 *ctlp++ = PCSSIG;
3640                 infop = (siginfo_t *)ctlp;
3641                 (void) memset(infop, 0, sizeof (*infop));
3642                 infop->si_signo = sig;
3643                 ctlp += sizeof (siginfo_t) / sizeof (long);
3644         }
3645 
3646         *ctlp++ = PCRUN;
3647         *ctlp++ = flags;
3648         size = (char *)ctlp - (char *)ctl;
3649 
3650         L->lwp_proc->info_valid = 0; /* will need to update map and file info */
3651         L->lwp_proc->state = PS_RUN;
3652         L->lwp_state = PS_RUN;
3653 
3654         if (write(ctlfd, ctl, size) != size) {
3655                 /* Pretend that a job-stopped LWP is running */
3656                 if (errno != EBUSY || L->lwp_status.pr_why != PR_JOBCONTROL)
3657                         return (Lstopstatus(L, PCNULL, 0));
3658         }
3659 
3660         return (0);
3661 }
3662 
3663 int
3664 Lclearsig(struct ps_lwphandle *L)
3665 {
3666         int ctlfd = L->lwp_ctlfd;
3667         long ctl = PCCSIG;
3668 
3669         if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
3670                 return (-1);
3671         L->lwp_status.pr_cursig = 0;
3672         return (0);
3673 }
3674 
3675 int
3676 Lclearfault(struct ps_lwphandle *L)
3677 {
3678         int ctlfd = L->lwp_ctlfd;
3679         long ctl = PCCFAULT;
3680 
3681         if (write(ctlfd, &ctl, sizeof (ctl)) != sizeof (ctl))
3682                 return (-1);
3683         return (0);
3684 }
3685 
3686 /*
3687  * Step over a breakpoint, i.e., execute the instruction that
3688  * really belongs at the breakpoint location (the current %pc)
3689  * and leave the LWP stopped at the next instruction.
3690  */
3691 int
3692 Lxecbkpt(struct ps_lwphandle *L, ulong_t saved)
3693 {
3694         struct ps_prochandle *P = L->lwp_proc;
3695         int rv, error;
3696 
3697         if (L->lwp_state != PS_STOP) {
3698                 errno = EBUSY;
3699                 return (-1);
3700         }
3701 
3702         Lsync(L);
3703         error = execute_bkpt(L->lwp_ctlfd,
3704             &P->status.pr_flttrace, &L->lwp_status.pr_lwphold,
3705             L->lwp_status.pr_reg[R_PC], saved);
3706         rv = Lstopstatus(L, PCNULL, 0);
3707 
3708         if (error != 0) {
3709                 if (L->lwp_status.pr_why == PR_JOBCONTROL &&
3710                     error == EBUSY) {   /* jobcontrol stop -- back off */
3711                         L->lwp_state = PS_RUN;
3712                         return (0);
3713                 }
3714                 if (error == ENOENT)
3715                         return (0);
3716                 errno = error;
3717                 return (-1);
3718         }
3719 
3720         return (rv);
3721 }
3722 
3723 /*
3724  * Step over a watchpoint, i.e., execute the instruction that was stopped by
3725  * the watchpoint, and then leave the LWP stopped at the next instruction.
3726  */
3727 int
3728 Lxecwapt(struct ps_lwphandle *L, const prwatch_t *wp)
3729 {
3730         struct ps_prochandle *P = L->lwp_proc;
3731         int rv, error;
3732 
3733         if (L->lwp_state != PS_STOP) {
3734                 errno = EBUSY;
3735                 return (-1);
3736         }
3737 
3738         Lsync(L);
3739         error = execute_wapt(L->lwp_ctlfd,
3740             &P->status.pr_flttrace, &L->lwp_status.pr_lwphold, wp);
3741         rv = Lstopstatus(L, PCNULL, 0);
3742 
3743         if (error != 0) {
3744                 if (L->lwp_status.pr_why == PR_JOBCONTROL &&
3745                     error == EBUSY) {   /* jobcontrol stop -- back off */
3746                         L->lwp_state = PS_RUN;
3747                         return (0);
3748                 }
3749                 if (error == ENOENT)
3750                         return (0);
3751                 errno = error;
3752                 return (-1);
3753         }
3754 
3755         return (rv);
3756 }
3757 
3758 int
3759 Lstack(struct ps_lwphandle *L, stack_t *stkp)
3760 {
3761         struct ps_prochandle *P = L->lwp_proc;
3762         uintptr_t addr = L->lwp_status.pr_ustack;
3763 
3764         if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
3765                 if (Pread(P, stkp, sizeof (*stkp), addr) != sizeof (*stkp))
3766                         return (-1);
3767 #ifdef _LP64
3768         } else {
3769                 stack32_t stk32;
3770 
3771                 if (Pread(P, &stk32, sizeof (stk32), addr) != sizeof (stk32))
3772                         return (-1);
3773 
3774                 stack_32_to_n(&stk32, stkp);
3775 #endif
3776         }
3777 
3778         return (0);
3779 }
3780 
3781 int
3782 Lmain_stack(struct ps_lwphandle *L, stack_t *stkp)
3783 {
3784         struct ps_prochandle *P = L->lwp_proc;
3785 
3786         if (Lstack(L, stkp) != 0)
3787                 return (-1);
3788 
3789         /*
3790          * If the SS_ONSTACK flag is set then this LWP is operating on the
3791          * alternate signal stack. We can recover the original stack from
3792          * pr_oldcontext.
3793          */
3794         if (!(stkp->ss_flags & SS_ONSTACK))
3795                 return (0);
3796 
3797         if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
3798                 ucontext_t *ctxp = (void *)L->lwp_status.pr_oldcontext;
3799 
3800                 if (Pread(P, stkp, sizeof (*stkp),
3801                     (uintptr_t)&ctxp->uc_stack) != sizeof (*stkp))
3802                         return (-1);
3803 #ifdef _LP64
3804         } else {
3805                 ucontext32_t *ctxp = (void *)L->lwp_status.pr_oldcontext;
3806                 stack32_t stk32;
3807 
3808                 if (Pread(P, &stk32, sizeof (stk32),
3809                     (uintptr_t)&ctxp->uc_stack) != sizeof (stk32))
3810                         return (-1);
3811 
3812                 stack_32_to_n(&stk32, stkp);
3813 #endif
3814         }
3815 
3816         return (0);
3817 }
3818 
3819 int
3820 Lalt_stack(struct ps_lwphandle *L, stack_t *stkp)
3821 {
3822         if (L->lwp_status.pr_altstack.ss_flags & SS_DISABLE) {
3823                 errno = ENODATA;
3824                 return (-1);
3825         }
3826 
3827         *stkp = L->lwp_status.pr_altstack;
3828 
3829         return (0);
3830 }
3831 
3832 /*
3833  * Add a mapping to the given proc handle.  Resizes the array as appropriate and
3834  * manages reference counts on the given file_info_t.
3835  *
3836  * The 'map_relocate' member is used to tell Psort_mappings() that the
3837  * associated file_map pointer needs to be relocated after the mappings have
3838  * been sorted.  It is only set for the first mapping, and has no meaning
3839  * outside these two functions.
3840  */
3841 int
3842 Padd_mapping(struct ps_prochandle *P, off64_t off, file_info_t *fp,
3843     prmap_t *pmap)
3844 {
3845         map_info_t *mp;
3846 
3847         if (P->map_count == P->map_alloc) {
3848                 size_t next = P->map_alloc ? P->map_alloc * 2 : 16;
3849 
3850                 if ((P->mappings = realloc(P->mappings,
3851                     next * sizeof (map_info_t))) == NULL)
3852                         return (-1);
3853 
3854                 P->map_alloc = next;
3855         }
3856 
3857         mp = &P->mappings[P->map_count++];
3858 
3859         mp->map_offset = off;
3860         mp->map_pmap = *pmap;
3861         mp->map_relocate = 0;
3862         if ((mp->map_file = fp) != NULL) {
3863                 if (fp->file_map == NULL) {
3864                         fp->file_map = mp;
3865                         mp->map_relocate = 1;
3866                 }
3867                 fp->file_ref++;
3868         }
3869 
3870         return (0);
3871 }
3872 
3873 static int
3874 map_sort(const void *a, const void *b)
3875 {
3876         const map_info_t *ap = a, *bp = b;
3877 
3878         if (ap->map_pmap.pr_vaddr < bp->map_pmap.pr_vaddr)
3879                 return (-1);
3880         else if (ap->map_pmap.pr_vaddr > bp->map_pmap.pr_vaddr)
3881                 return (1);
3882         else
3883                 return (0);
3884 }
3885 
3886 /*
3887  * Sort the current set of mappings.  Should be called during target
3888  * initialization after all calls to Padd_mapping() have been made.
3889  */
3890 void
3891 Psort_mappings(struct ps_prochandle *P)
3892 {
3893         int i;
3894         map_info_t *mp;
3895 
3896         qsort(P->mappings, P->map_count, sizeof (map_info_t), map_sort);
3897 
3898         /*
3899          * Update all the file_map pointers to refer to the new locations.
3900          */
3901         for (i = 0; i < P->map_count; i++) {
3902                 mp = &P->mappings[i];
3903                 if (mp->map_relocate)
3904                         mp->map_file->file_map = mp;
3905                 mp->map_relocate = 0;
3906         }
3907 }
3908 
3909 struct ps_prochandle *
3910 Pgrab_ops(pid_t pid, void *data, const ps_ops_t *ops, int flags)
3911 {
3912         struct ps_prochandle *P;
3913 
3914         if ((P = calloc(1, sizeof (*P))) == NULL) {
3915                 return (NULL);
3916         }
3917 
3918         Pinit_ops(&P->ops, ops);
3919         (void) mutex_init(&P->proc_lock, USYNC_THREAD, NULL);
3920         P->pid = pid;
3921         P->state = PS_STOP;
3922         P->asfd = -1;
3923         P->ctlfd = -1;
3924         P->statfd = -1;
3925         P->agentctlfd = -1;
3926         P->agentstatfd = -1;
3927         Pinitsym(P);
3928         P->data = data;
3929         Pread_status(P);
3930 
3931         if (flags & PGRAB_INCORE) {
3932                 P->flags |= INCORE;
3933         }
3934 
3935         return (P);
3936 }