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