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