1 /*
   2  * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include "jni.h"
  27 #include "jni_util.h"
  28 #include "java_lang_ProcessHandleImpl.h"
  29 #include "java_lang_ProcessHandleImpl_Info.h"
  30 
  31 #include "ProcessHandleImpl_unix.h"
  32 
  33 
  34 #include <stdio.h>
  35 #include <errno.h>
  36 #include <fcntl.h>
  37 #include <pwd.h>
  38 #include <signal.h>
  39 #include <stdlib.h>
  40 #include <unistd.h>
  41 #include <string.h>
  42 #include <dirent.h>
  43 #include <ctype.h>
  44 #include <limits.h>
  45 #include <sys/types.h>
  46 #include <sys/stat.h>
  47 #include <sys/wait.h>
  48 
  49 #ifdef _AIX
  50 #include <sys/procfs.h>
  51 #endif
  52 #ifdef __solaris__
  53 #include <procfs.h>
  54 #endif
  55 
  56 /**
  57  * This file contains the implementation of the native ProcessHandleImpl
  58  * functions which are common to all Unix variants.
  59  *
  60  * The currently supported Unix variants are Solaris, Linux, MaxOS X and AIX.
  61  * The various similarities and differences between these systems make it hard
  62  * to find a clear boundary between platform specific and shared code.
  63  *
  64  * In order to ease code sharing between the platforms while still keeping the
  65  * code as clean as possible (i.e. free of preprocessor macros) we use the
  66  * following source code layout (remember that ProcessHandleImpl_unix.c will
  67  * be compiled on EVERY Unix platform while ProcessHandleImpl_<os>.c will be
  68  * only compiled on the specific OS):
  69  *
  70  * - all the JNI wrappers for the ProcessHandleImpl functions go into this file
  71  * - if their implementation is common on ALL the supported Unix platforms it
  72  *   goes right into the JNI wrappers
  73  * - if the whole function or substantial parts of it are platform dependent,
  74  *   the implementation goes into os_<function_name> functions in
  75  *   ProcessHandleImpl_<os>.c
  76  * - if at least two platforms implement an os_<function_name> function in the
  77  *   same way, this implementation is factored out into unix_<function_name>,
  78  *   placed into this file and called from the corresponding os_<function_name>
  79  *   function.
  80  * - For convenience, all the os_ and unix_ functions are declared in
  81  *   ProcessHandleImpl_unix.h which is included into every
  82  *   ProcessHandleImpl_<os>.c file.
  83  *
  84  * Example 1:
  85  * ----------
  86  * The implementation of Java_java_lang_ProcessHandleImpl_initNative()
  87  * is the same on all platforms except on Linux where it initilizes one
  88  * additional field. So we place the implementation right into
  89  * Java_java_lang_ProcessHandleImpl_initNative() but add call to
  90  * os_init() at the end of the function which is empty on all platforms
  91  * except Linux where it performs the additionally initializations.
  92  *
  93  * Example 2:
  94  * ----------
  95  * The implementation of Java_java_lang_ProcessHandleImpl_00024Info_info0 is
  96  * the same on Solaris and AIX but different on Linux and MacOSX. We therefore
  97  * simply call the two helpers os_getParentPid() and os_getCmdlineInfo(). The
  98  * Linux and MaxOS X versions of these functions (in the corresponding files
  99  * ProcessHandleImpl_linux.c and ProcessHandleImpl_macosx.c) directly contain
 100  * the platform specific implementations while the Solaris and AIX
 101  * implementations simply call back to unix_getParentPid() and
 102  * unix_getCmdlineInfo() which are implemented right in this file.
 103  * The remaining code of Java_java_lang_ProcessHandleImpl_00024Info_info0 which
 104  * is common on all Unix platfroms has been extracted into unix_getUserInfo().
 105  *
 106  * The term "same implementation" is still a question of interpretation. It my
 107  * be acceptable to have a few ifdef'ed lines if that allows the sharing of a
 108  * huge function. On the other hand, if the platform specific code in a shared
 109  * function grows over a certain limit, it may be better to refactor that
 110  * functionality into corresponding, platform-specific os_ functions.
 111  */
 112 
 113 
 114 #ifndef WIFEXITED
 115 #define WIFEXITED(status) (((status)&0xFF) == 0)
 116 #endif
 117 
 118 #ifndef WEXITSTATUS
 119 #define WEXITSTATUS(status) (((status)>>8)&0xFF)
 120 #endif
 121 
 122 #ifndef WIFSIGNALED
 123 #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0)
 124 #endif
 125 
 126 #ifndef WTERMSIG
 127 #define WTERMSIG(status) ((status)&0x7F)
 128 #endif
 129 
 130 #ifdef __solaris__
 131 /* The child exited because of a signal.
 132  * The best value to return is 0x80 + signal number,
 133  * because that is what all Unix shells do, and because
 134  * it allows callers to distinguish between process exit and
 135  * process death by signal.
 136  * Unfortunately, the historical behavior on Solaris is to return
 137  * the signal number, and we preserve this for compatibility. */
 138 #define WTERMSIG_RETURN(status) WTERMSIG(status);
 139 #else
 140 #define WTERMSIG_RETURN(status) (WTERMSIG(status) + 0x80);
 141 #endif
 142 
 143 #define RESTARTABLE(_cmd, _result) do { \
 144   do { \
 145     _result = _cmd; \
 146   } while((_result == -1) && (errno == EINTR)); \
 147 } while(0)
 148 
 149 #define RESTARTABLE_RETURN_PTR(_cmd, _result) do { \
 150   do { \
 151     _result = _cmd; \
 152   } while((_result == NULL) && (errno == EINTR)); \
 153 } while(0)
 154 
 155 
 156 /* Field id for jString 'command' in java.lang.ProcessHandleImpl.Info */
 157 jfieldID ProcessHandleImpl_Info_commandID;
 158 
 159 /* Field id for jString[] 'arguments' in java.lang.ProcessHandleImpl.Info */
 160 jfieldID ProcessHandleImpl_Info_argumentsID;
 161 
 162 /* Field id for jlong 'totalTime' in java.lang.ProcessHandleImpl.Info */
 163 jfieldID ProcessHandleImpl_Info_totalTimeID;
 164 
 165 /* Field id for jlong 'startTime' in java.lang.ProcessHandleImpl.Info */
 166 jfieldID ProcessHandleImpl_Info_startTimeID;
 167 
 168 /* Field id for jString 'user' in java.lang.ProcessHandleImpl.Info */
 169 jfieldID ProcessHandleImpl_Info_userID;
 170 
 171 /* static value for clock ticks per second. */
 172 long clock_ticks_per_second;
 173 
 174 /**************************************************************
 175  * Static method to initialize field IDs and the ticks per second rate.
 176  *
 177  * Class:     java_lang_ProcessHandleImpl_Info
 178  * Method:    initIDs
 179  * Signature: ()V
 180  */
 181 JNIEXPORT void JNICALL
 182 Java_java_lang_ProcessHandleImpl_00024Info_initIDs(JNIEnv *env, jclass clazz) {
 183 
 184     CHECK_NULL(ProcessHandleImpl_Info_commandID =
 185             (*env)->GetFieldID(env, clazz, "command", "Ljava/lang/String;"));
 186     CHECK_NULL(ProcessHandleImpl_Info_argumentsID =
 187             (*env)->GetFieldID(env, clazz, "arguments", "[Ljava/lang/String;"));
 188     CHECK_NULL(ProcessHandleImpl_Info_totalTimeID =
 189             (*env)->GetFieldID(env, clazz, "totalTime", "J"));
 190     CHECK_NULL(ProcessHandleImpl_Info_startTimeID =
 191             (*env)->GetFieldID(env, clazz, "startTime", "J"));
 192     CHECK_NULL(ProcessHandleImpl_Info_userID =
 193             (*env)->GetFieldID(env, clazz, "user", "Ljava/lang/String;"));
 194 }
 195 
 196 /**************************************************************
 197  * Static method to initialize the ticks per second rate.
 198  *
 199  * Class:     java_lang_ProcessHandleImpl
 200  * Method:    initNative
 201  * Signature: ()V
 202  */
 203 JNIEXPORT void JNICALL
 204 Java_java_lang_ProcessHandleImpl_initNative(JNIEnv *env, jclass clazz) {
 205     clock_ticks_per_second = sysconf(_SC_CLK_TCK);
 206     os_initNative(env, clazz);
 207 }
 208 
 209 /* Block until a child process exits and return its exit code.
 210  * Note, can only be called once for any given pid if reapStatus = true.
 211  *
 212  * Class:     java_lang_ProcessHandleImpl
 213  * Method:    waitForProcessExit0
 214  * Signature: (JZ)I
 215  */
 216 JNIEXPORT jint JNICALL
 217 Java_java_lang_ProcessHandleImpl_waitForProcessExit0(JNIEnv* env,
 218                                                      jclass junk,
 219                                                      jlong jpid,
 220                                                      jboolean reapStatus) {
 221     pid_t pid = (pid_t)jpid;
 222     errno = 0;
 223 
 224     if (reapStatus != JNI_FALSE) {
 225         /* Wait for the child process to exit.
 226          * waitpid() is standard, so use it on all POSIX platforms.
 227          * It is known to work when blocking to wait for the pid
 228          * This returns immediately if the child has already exited.
 229          */
 230         int status;
 231         while (waitpid(pid, &status, 0) < 0) {
 232             switch (errno) {
 233                 case ECHILD: return 0;
 234                 case EINTR: break;
 235                 default: return -1;
 236             }
 237         }
 238 
 239         if (WIFEXITED(status)) {
 240             return WEXITSTATUS(status);
 241         } else if (WIFSIGNALED(status)) {
 242             return WTERMSIG_RETURN(status);
 243         } else {
 244             return status;
 245         }
 246      } else {
 247         /*
 248          * Wait for the child process to exit without reaping the exitValue.
 249          * waitid() is standard on all POSIX platforms.
 250          * Note: waitid on Mac OS X 10.7 seems to be broken;
 251          * it does not return the exit status consistently.
 252          */
 253         siginfo_t siginfo;
 254         int options = WEXITED |  WNOWAIT;
 255         memset(&siginfo, 0, sizeof siginfo);
 256         while (waitid(P_PID, pid, &siginfo, options) < 0) {
 257             switch (errno) {
 258             case ECHILD: return 0;
 259             case EINTR: break;
 260             default: return -1;
 261             }
 262         }
 263 
 264         if (siginfo.si_code == CLD_EXITED) {
 265              /*
 266               * The child exited normally; get its exit code.
 267               */
 268              return siginfo.si_status;
 269         } else if (siginfo.si_code == CLD_KILLED || siginfo.si_code == CLD_DUMPED) {
 270              return WTERMSIG_RETURN(siginfo.si_status);
 271         } else {
 272              /*
 273               * Unknown exit code; pass it through.
 274               */
 275              return siginfo.si_status;
 276         }
 277     }
 278 }
 279 
 280 /*
 281  * Class:     java_lang_ProcessHandleImpl
 282  * Method:    getCurrentPid0
 283  * Signature: ()J
 284  */
 285 JNIEXPORT jlong JNICALL
 286 Java_java_lang_ProcessHandleImpl_getCurrentPid0(JNIEnv *env, jclass clazz) {
 287     pid_t pid = getpid();
 288     return (jlong) pid;
 289 }
 290 
 291 /*
 292  * Class:     java_lang_ProcessHandleImpl
 293  * Method:    destroy0
 294  * Signature: (JJZ)Z
 295  */
 296 JNIEXPORT jboolean JNICALL
 297 Java_java_lang_ProcessHandleImpl_destroy0(JNIEnv *env,
 298                                           jobject obj,
 299                                           jlong jpid,
 300                                           jlong startTime,
 301                                           jboolean force) {
 302     pid_t pid = (pid_t) jpid;
 303     int sig = (force == JNI_TRUE) ? SIGKILL : SIGTERM;
 304     jlong start = Java_java_lang_ProcessHandleImpl_isAlive0(env, obj, jpid);
 305 
 306     if (start == startTime || start == 0 || startTime == 0) {
 307         return (kill(pid, sig) < 0) ? JNI_FALSE : JNI_TRUE;
 308     } else {
 309         return JNI_FALSE;
 310     }
 311 }
 312 
 313 /*
 314  * Returns the children of the requested pid and optionally each parent and
 315  * start time.
 316  * Accumulates any process who parent pid matches.
 317  * The resulting pids are stored into the array of longs.
 318  * The number of pids is returned if they all fit.
 319  * If the array is too short, the negative of the desired length is returned.
 320  * Class:     java_lang_ProcessHandleImpl
 321  * Method:    getProcessPids0
 322  * Signature: (J[J[J[J)I
 323  */
 324 JNIEXPORT jint JNICALL
 325 Java_java_lang_ProcessHandleImpl_getProcessPids0(JNIEnv *env,
 326                                                  jclass clazz,
 327                                                  jlong jpid,
 328                                                  jlongArray jarray,
 329                                                  jlongArray jparentArray,
 330                                                  jlongArray jstimesArray) {
 331     return os_getChildren(env, jpid, jarray, jparentArray, jstimesArray);
 332 }
 333 
 334 /*
 335  * Fill in the Info object from the OS information about the process.
 336  *
 337  * Class:     java_lang_ProcessHandleImpl_Info
 338  * Method:    info0
 339  * Signature: (Ljava/lang/ProcessHandle/Info;J)I
 340  */
 341 JNIEXPORT void JNICALL
 342 Java_java_lang_ProcessHandleImpl_00024Info_info0(JNIEnv *env,
 343                                                  jobject jinfo,
 344                                                  jlong jpid) {
 345     pid_t pid = (pid_t) jpid;
 346     pid_t ppid;
 347     jlong totalTime = -1L;
 348     jlong startTime = -1L;
 349 
 350     ppid = os_getParentPid(env, pid,  &totalTime, &startTime);
 351     if (ppid > 0) {
 352         (*env)->SetLongField(env, jinfo, ProcessHandleImpl_Info_totalTimeID, totalTime);
 353         JNU_CHECK_EXCEPTION(env);
 354 
 355         (*env)->SetLongField(env, jinfo, ProcessHandleImpl_Info_startTimeID, startTime);
 356         JNU_CHECK_EXCEPTION(env);
 357     }
 358     unix_getUserInfo(env, jinfo, pid);
 359     os_getCmdlineInfo(env, jinfo, pid);
 360 }
 361 
 362 /*
 363  * Check if a process is alive.
 364  * Return the start time (ms since 1970) if it is available.
 365  * If the start time is not available return 0.
 366  * If the pid is invalid, return -1.
 367  *
 368  * Class:     java_lang_ProcessHandleImpl
 369  * Method:    isAlive0
 370  * Signature: (J)J
 371  */
 372 JNIEXPORT jlong JNICALL
 373 Java_java_lang_ProcessHandleImpl_isAlive0(JNIEnv *env, jobject obj, jlong jpid) {
 374     pid_t pid = (pid_t) jpid;
 375     jlong startTime = 0L;
 376     jlong totalTime = 0L;
 377     pid_t ppid = os_getParentPid(env, pid, &totalTime, &startTime);
 378     return (ppid <= 0) ? -1 : startTime;
 379 }
 380 
 381 /*
 382  * Returns the parent pid of the requested pid.
 383  * The start time of the process must match (or be ANY).
 384  *
 385  * Class:     java_lang_ProcessHandleImpl
 386  * Method:    parent0
 387  * Signature: (JJ)J
 388  */
 389 JNIEXPORT jlong JNICALL
 390 Java_java_lang_ProcessHandleImpl_parent0(JNIEnv *env,
 391                                         jobject obj,
 392                                         jlong jpid,
 393                                         jlong startTime) {
 394     pid_t pid = (pid_t) jpid;
 395     pid_t ppid;
 396 
 397     pid_t mypid = getpid();
 398     if (pid == mypid) {
 399         ppid = getppid();
 400     } else {
 401         jlong start = 0L;;
 402         jlong total = 0L;        // unused
 403         ppid = os_getParentPid(env, pid, &total, &start);
 404         if (start != startTime && start != 0 && startTime != 0) {
 405             ppid = -1;
 406         }
 407     }
 408     return (jlong) ppid;
 409 }
 410 
 411 /**
 412  * Construct the argument array by parsing the arguments from the sequence
 413  * of arguments. The zero'th arg is the command executable but it will only
 414  * be used if the 'cmdexe' argument is NULL.
 415  */
 416 void unix_fillArgArray(JNIEnv *env, jobject jinfo, int nargs,
 417                        char *cp, char *argsEnd, jstring cmdexe) {
 418     jobject argsArray;
 419     int i;
 420 
 421     if (cmdexe == NULL && nargs > 0) {
 422         // Create a string from arg[0]
 423         CHECK_NULL((cmdexe = JNU_NewStringPlatform(env, cp)));
 424     }
 425     (*env)->SetObjectField(env, jinfo, ProcessHandleImpl_Info_commandID, cmdexe);
 426     JNU_CHECK_EXCEPTION(env);
 427 
 428     if (nargs > 1) {
 429         // Create a String array for nargs-1 elements
 430         argsArray = (*env)->NewObjectArray(env, nargs - 1, JNU_ClassString(env), NULL);
 431         CHECK_NULL(argsArray);
 432 
 433         for (i = 0; i < nargs - 1; i++) {
 434             jstring str = NULL;
 435 
 436             cp += strlen(cp) + 1;
 437             if (cp > argsEnd || *cp == '\0') {
 438                 return;  // Off the end pointer or an empty argument is an error
 439             }
 440 
 441             CHECK_NULL((str = JNU_NewStringPlatform(env, cp)));
 442 
 443             (*env)->SetObjectArrayElement(env, argsArray, i, str);
 444             JNU_CHECK_EXCEPTION(env);
 445         }
 446         (*env)->SetObjectField(env, jinfo, ProcessHandleImpl_Info_argumentsID, argsArray);
 447         JNU_CHECK_EXCEPTION(env);
 448     }
 449 }
 450 
 451 /* Size of password or group entry when not available via sysconf */
 452 #define ENT_BUF_SIZE   1024
 453 
 454 void unix_getUserInfo(JNIEnv* env, jobject jinfo, pid_t pid) {
 455     int result = 0;
 456     int buflen;
 457     char* pwbuf;
 458     jstring name = NULL;
 459     uid_t uid;
 460 
 461     if ((int)(uid = os_getUID(pid)) < 0) {
 462         return;
 463     }
 464     /* allocate buffer for password record */
 465     buflen = (int)sysconf(_SC_GETPW_R_SIZE_MAX);
 466     if (buflen == -1) {
 467         buflen = ENT_BUF_SIZE;
 468     }
 469     pwbuf = (char*)malloc(buflen);
 470     if (pwbuf == NULL) {
 471         JNU_ThrowOutOfMemoryError(env, "Unable to open getpwent");
 472     } else {
 473         struct passwd pwent;
 474         struct passwd* p = NULL;
 475 
 476 #ifdef __solaris__
 477         RESTARTABLE_RETURN_PTR(getpwuid_r(uid, &pwent, pwbuf, (size_t)buflen), p);
 478 #else
 479         RESTARTABLE(getpwuid_r(uid, &pwent, pwbuf, (size_t)buflen, &p), result);
 480 #endif
 481 
 482         // Create the Java String if a name was found
 483         if (result == 0 && p != NULL &&
 484             p->pw_name != NULL && *(p->pw_name) != '\0') {
 485             name = JNU_NewStringPlatform(env, p->pw_name);
 486         }
 487         free(pwbuf);
 488     }
 489     if (name != NULL) {
 490         (*env)->SetObjectField(env, jinfo, ProcessHandleImpl_Info_userID, name);
 491     }
 492 }
 493 
 494 /*
 495  * The following fuctions are common on Solaris, Linux and AIX.
 496  */
 497 
 498 #if defined(__solaris__) || defined (__linux__) || defined(_AIX)
 499 
 500 /*
 501  * Returns the children of the requested pid and optionally each parent and
 502  * start time.
 503  * Reads /proc and accumulates any process who parent pid matches.
 504  * The resulting pids are stored into the array of longs.
 505  * The number of pids is returned if they all fit.
 506  * If the array is too short, the negative of the desired length is returned.
 507  */
 508 jint unix_getChildren(JNIEnv *env, jlong jpid, jlongArray jarray,
 509                       jlongArray jparentArray, jlongArray jstimesArray) {
 510     DIR* dir;
 511     struct dirent* ptr;
 512     pid_t pid = (pid_t) jpid;
 513     jlong* pids = NULL;
 514     jlong* ppids = NULL;
 515     jlong* stimes = NULL;
 516     jsize parentArraySize = 0;
 517     jsize arraySize = 0;
 518     jsize stimesSize = 0;
 519     jsize count = 0;
 520 
 521     arraySize = (*env)->GetArrayLength(env, jarray);
 522     JNU_CHECK_EXCEPTION_RETURN(env, -1);
 523     if (jparentArray != NULL) {
 524         parentArraySize = (*env)->GetArrayLength(env, jparentArray);
 525         JNU_CHECK_EXCEPTION_RETURN(env, -1);
 526 
 527         if (arraySize != parentArraySize) {
 528             JNU_ThrowIllegalArgumentException(env, "array sizes not equal");
 529             return 0;
 530         }
 531     }
 532     if (jstimesArray != NULL) {
 533         stimesSize = (*env)->GetArrayLength(env, jstimesArray);
 534         JNU_CHECK_EXCEPTION_RETURN(env, -1);
 535 
 536         if (arraySize != stimesSize) {
 537             JNU_ThrowIllegalArgumentException(env, "array sizes not equal");
 538             return 0;
 539         }
 540     }
 541 
 542     /*
 543      * To locate the children we scan /proc looking for files that have a
 544      * position integer as a filename.
 545      */
 546     if ((dir = opendir("/proc")) == NULL) {
 547         JNU_ThrowByNameWithLastError(env,
 548             "java/lang/RuntimeException", "Unable to open /proc");
 549         return -1;
 550     }
 551 
 552     do { // Block to break out of on Exception
 553         pids = (*env)->GetLongArrayElements(env, jarray, NULL);
 554         if (pids == NULL) {
 555             break;
 556         }
 557         if (jparentArray != NULL) {
 558             ppids  = (*env)->GetLongArrayElements(env, jparentArray, NULL);
 559             if (ppids == NULL) {
 560                 break;
 561             }
 562         }
 563         if (jstimesArray != NULL) {
 564             stimes  = (*env)->GetLongArrayElements(env, jstimesArray, NULL);
 565             if (stimes == NULL) {
 566                 break;
 567             }
 568         }
 569 
 570         while ((ptr = readdir(dir)) != NULL) {
 571             pid_t ppid = 0;
 572             jlong totalTime = 0L;
 573             jlong startTime = 0L;
 574 
 575             /* skip files that aren't numbers */
 576             pid_t childpid = (pid_t) atoi(ptr->d_name);
 577             if ((int) childpid <= 0) {
 578                 continue;
 579             }
 580 
 581             // Get the parent pid, and start time
 582             ppid = os_getParentPid(env, childpid, &totalTime, &startTime);
 583             if (ppid > 0 && (pid == 0 || ppid == pid)) {
 584                 if (count < arraySize) {
 585                     // Only store if it fits
 586                     pids[count] = (jlong) childpid;
 587 
 588                     if (ppids != NULL) {
 589                         // Store the parentPid
 590                         ppids[count] = (jlong) ppid;
 591                     }
 592                     if (stimes != NULL) {
 593                         // Store the process start time
 594                         stimes[count] = startTime;
 595                     }
 596                 }
 597                 count++; // Count to tabulate size needed
 598             }
 599         }
 600     } while (0);
 601 
 602     if (pids != NULL) {
 603         (*env)->ReleaseLongArrayElements(env, jarray, pids, 0);
 604     }
 605     if (ppids != NULL) {
 606         (*env)->ReleaseLongArrayElements(env, jparentArray, ppids, 0);
 607     }
 608     if (stimes != NULL) {
 609         (*env)->ReleaseLongArrayElements(env, jstimesArray, stimes, 0);
 610     }
 611 
 612     closedir(dir);
 613     // If more pids than array had size for; count will be greater than array size
 614     return count;
 615 }
 616 
 617 #endif // defined(__solaris__) || defined (__linux__) || defined(_AIX)
 618 
 619 /*
 620  * The following fuctions are common on Solaris and AIX.
 621  */
 622 
 623 #if defined(__solaris__) || defined(_AIX)
 624 
 625 /**
 626  * Helper function to get the 'psinfo_t' data from "/proc/%d/psinfo".
 627  * Returns 0 on success and -1 on error.
 628  */
 629 static int getPsinfo(pid_t pid, psinfo_t *psinfo) {
 630     FILE* fp;
 631     char fn[32];
 632     int ret;
 633 
 634     /*
 635      * Try to open /proc/%d/psinfo
 636      */
 637     snprintf(fn, sizeof fn, "/proc/%d/psinfo", pid);
 638     fp = fopen(fn, "r");
 639     if (fp == NULL) {
 640         return -1;
 641     }
 642 
 643     ret = fread(psinfo, 1, sizeof(psinfo_t), fp);
 644     fclose(fp);
 645     if (ret < sizeof(psinfo_t)) {
 646         return -1;
 647     }
 648     return 0;
 649 }
 650 
 651 /**
 652  * Return the uid of a process or -1 on error
 653  */
 654 uid_t unix_getUID(pid_t pid) {
 655     psinfo_t psinfo;
 656 
 657     if (getPsinfo(pid, &psinfo) == 0) {
 658         return psinfo.pr_uid;
 659     }
 660     return -1;
 661 }
 662 
 663 /**
 664  * Read /proc/<pid>/psinfo and return the ppid, total cputime and start time.
 665  * Return: -1 is fail;  zero is unknown; >  0 is parent pid
 666  */
 667 pid_t unix_getParentPid(JNIEnv *env, pid_t pid,
 668                         jlong *totalTime, jlong* startTime) {
 669     psinfo_t psinfo;
 670 
 671     if (getPsinfo(pid, &psinfo) < 0) {
 672         return -1;
 673     }
 674 
 675     *totalTime = psinfo.pr_time.tv_sec * 1000000000L + psinfo.pr_time.tv_nsec;
 676 
 677     *startTime = psinfo.pr_start.tv_sec * (jlong)1000 +
 678                  psinfo.pr_start.tv_nsec / 1000000;
 679 
 680     return (pid_t) psinfo.pr_ppid;
 681 }
 682 
 683 void unix_getCmdlineInfo(JNIEnv *env, jobject jinfo, pid_t pid) {
 684     psinfo_t psinfo;
 685     char fn[32];
 686     char exePath[PATH_MAX];
 687     jstring str = NULL, cmdexe = NULL;
 688     int ret;
 689 
 690     /*
 691      * On Solris, the full path to the executable command is the link in
 692      * /proc/<pid>/paths/a.out. But it is only readable for processes we own.
 693      * On AIX, the readlink() call will simply fail because the link doesn't exist.
 694      */
 695     snprintf(fn, sizeof fn, "/proc/%d/path/a.out", pid);
 696     if ((ret = readlink(fn, exePath, PATH_MAX - 1)) > 0) {
 697         // null terminate and create String to store for command
 698         exePath[ret] = '\0';
 699         CHECK_NULL(cmdexe = JNU_NewStringPlatform(env, exePath));
 700     }
 701 
 702     /*
 703      * Now try to open /proc/%d/psinfo
 704      */
 705     if (getPsinfo(pid, &psinfo) < 0) {
 706         unix_fillArgArray(env, jinfo, 0, NULL, NULL, cmdexe);
 707     }
 708 
 709     /*
 710      * Now read psinfo.pr_psargs which contains the first PRARGSZ characters of the
 711      * argument list (i.e. arg[0] arg[1] ...). Unfortunately, PRARGSZ is usually set
 712      * to 80 characters only. Nevertheless it's better than nothing :)
 713      */
 714     {
 715         char prargs[PRARGSZ + 1];
 716         char *cp, *argsEnd;
 717         int nargs = 1;
 718         strncpy(prargs, psinfo.pr_psargs, PRARGSZ);
 719         prargs[PRARGSZ] = '\0';
 720         argsEnd = &prargs[strlen(prargs)];
 721         if (argsEnd == prargs) {
 722             /* If psinfo.pr_psargs didn't contain any strings, use psinfo.pr_fname
 723              * (which only contains the last component of exec()ed pathname) as a
 724              * last resort. This is true for AIX kernel processes for example.
 725              */
 726             strncpy(prargs, psinfo.pr_fname, PRARGSZ);
 727             prargs[PRARGSZ] = '\0';
 728             argsEnd = &prargs[strlen(prargs)];
 729         } else {
 730             /* The arguments are separeted by a single whitespace character but we want
 731              * them to be distinct, null-terminated strings. */
 732             for (cp = prargs; *cp != '\0'; cp++) {
 733                 if (*cp == ' ') {
 734                     *cp = '\0';
 735                     nargs++;
 736                 }
 737             }
 738         }
 739         unix_fillArgArray(env, jinfo, nargs, prargs, argsEnd, cmdexe);
 740     }
 741 }
 742 
 743 #endif // defined(__solaris__) || defined(_AIX)