Path: blob/master/src/java.base/linux/native/libjava/ProcessHandleImpl_linux.c
41119 views
/*1* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425#include "jni.h"26#include "jni_util.h"27#include "java_lang_ProcessHandleImpl.h"28#include "java_lang_ProcessHandleImpl_Info.h"2930#include "ProcessHandleImpl_unix.h"313233#include <fcntl.h>34#include <limits.h>35#include <stdlib.h>36#include <unistd.h>37#include <sys/types.h>38#include <sys/stat.h>3940#include <string.h>41#include <ctype.h>4243/*44* Implementation of native ProcessHandleImpl functions for Linux.45* See ProcessHandleImpl_unix.c for more details.46*/4748/* Signatures for internal OS specific functions. */49static long long getBoottime(JNIEnv *env);5051/* A static offset in milliseconds since boot. */52static long long bootTime_ms;53static long clock_ticks_per_second;54static int pageSize;5556void os_initNative(JNIEnv *env, jclass clazz) {57bootTime_ms = getBoottime(env);58clock_ticks_per_second = sysconf(_SC_CLK_TCK);59pageSize = sysconf(_SC_PAGESIZE);60}6162jint os_getChildren(JNIEnv *env, jlong jpid, jlongArray jarray,63jlongArray jparentArray, jlongArray jstimesArray) {64return unix_getChildren(env, jpid, jarray, jparentArray, jstimesArray);65}6667/**68* Read /proc/<pid>/stat and return the ppid, total cputime and start time.69* -1 is fail; >= 0 is parent pid70* 'total' will contain the running time of 'pid' in nanoseconds.71* 'start' will contain the start time of 'pid' in milliseconds since epoch.72*/73pid_t os_getParentPidAndTimings(JNIEnv *env, pid_t pid,74jlong *totalTime, jlong* startTime) {75FILE* fp;76char buffer[2048];77int statlen;78char fn[32];79char* s;80int parentPid;81long unsigned int utime = 0; // clock tics82long unsigned int stime = 0; // clock tics83long long unsigned int start = 0; // microseconds8485/*86* Try to stat and then open /proc/%d/stat87*/88snprintf(fn, sizeof fn, "/proc/%d/stat", pid);8990fp = fopen(fn, "r");91if (fp == NULL) {92return -1; // fail, no such /proc/pid/stat93}9495/*96* The format is: pid (command) state ppid ...97* As the command could be anything we must find the right most98* ")" and then skip the white spaces that follow it.99*/100statlen = fread(buffer, 1, (sizeof buffer - 1), fp);101fclose(fp);102if (statlen < 0) {103return -1; // parent pid is not available104}105106buffer[statlen] = '\0';107s = strchr(buffer, '(');108if (s == NULL) {109return -1; // parent pid is not available110}111// Found start of command, skip to end112s++;113s = strrchr(s, ')');114if (s == NULL) {115return -1; // parent pid is not available116}117s++;118119// Scan the needed fields from status, retaining only ppid(4),120// utime (14), stime(15), starttime(22)121if (4 != sscanf(s, " %*c %d %*d %*d %*d %*d %*d %*u %*u %*u %*u %lu %lu %*d %*d %*d %*d %*d %*d %llu",122&parentPid, &utime, &stime, &start)) {123return 0; // not all values parsed; return error124}125126*totalTime = (utime + stime) * (jlong)(1000000000 / clock_ticks_per_second);127128*startTime = bootTime_ms + ((start * 1000) / clock_ticks_per_second);129130return parentPid;131}132133void os_getCmdlineAndUserInfo(JNIEnv *env, jobject jinfo, pid_t pid) {134int fd;135int cmdlen = 0;136char *cmdline = NULL, *cmdEnd = NULL; // used for command line args and exe137char *args = NULL;138jstring cmdexe = NULL;139char fn[32];140struct stat64 stat_buf;141142/*143* Stat /proc/<pid> to get the user id144*/145snprintf(fn, sizeof fn, "/proc/%d", pid);146if (stat64(fn, &stat_buf) == 0) {147unix_getUserInfo(env, jinfo, stat_buf.st_uid);148JNU_CHECK_EXCEPTION(env);149}150151/*152* Try to open /proc/<pid>/cmdline153*/154strncat(fn, "/cmdline", sizeof fn - strnlen(fn, sizeof fn) - 1);155if ((fd = open(fn, O_RDONLY)) < 0) {156return;157}158159do { // Block to break out of on errors160int i, truncated = 0;161int count;162char *s;163164/*165* The path name read by readlink() is limited to PATH_MAX characters.166* The content of /proc/<pid>/cmdline is limited to PAGE_SIZE characters.167*/168cmdline = (char*)malloc((PATH_MAX > pageSize ? PATH_MAX : pageSize) + 1);169if (cmdline == NULL) {170break;171}172173/*174* On Linux, the full path to the executable command is the link in175* /proc/<pid>/exe. But it is only readable for processes we own.176*/177snprintf(fn, sizeof fn, "/proc/%d/exe", pid);178if ((cmdlen = readlink(fn, cmdline, PATH_MAX)) > 0) {179// null terminate and create String to store for command180cmdline[cmdlen] = '\0';181cmdexe = JNU_NewStringPlatform(env, cmdline);182(*env)->ExceptionClear(env); // unconditionally clear any exception183}184185/*186* The command-line arguments appear as a set of strings separated by187* null bytes ('\0'), with a further null byte after the last188* string. The last string is only null terminated if the whole command189* line is not exceeding (PAGE_SIZE - 1) characters.190*/191cmdlen = 0;192s = cmdline;193while ((count = read(fd, s, pageSize - cmdlen)) > 0) {194cmdlen += count;195s += count;196}197if (count < 0) {198break;199}200// We have to null-terminate because the process may have changed argv[]201// or because the content in /proc/<pid>/cmdline is truncated.202cmdline[cmdlen] = '\0';203if (cmdlen == pageSize && cmdline[pageSize - 1] != '\0') {204truncated = 1;205} else if (cmdlen == 0) {206// /proc/<pid>/cmdline was empty. This usually happens for kernel processes207// like '[kthreadd]'. We could try to read /proc/<pid>/comm in the future.208}209if (cmdlen > 0 && (cmdexe == NULL || truncated)) {210// We have no exact command or the arguments are truncated.211// In this case we save the command line from /proc/<pid>/cmdline.212args = (char*)malloc(pageSize + 1);213if (args != NULL) {214memcpy(args, cmdline, cmdlen + 1);215for (i = 0; i < cmdlen; i++) {216if (args[i] == '\0') {217args[i] = ' ';218}219}220}221}222i = 0;223if (!truncated) {224// Count the arguments225cmdEnd = &cmdline[cmdlen];226for (s = cmdline; *s != '\0' && (s < cmdEnd); i++) {227s += strnlen(s, (cmdEnd - s)) + 1;228}229}230unix_fillArgArray(env, jinfo, i, cmdline, cmdEnd, cmdexe, args);231} while (0);232233if (cmdline != NULL) {234free(cmdline);235}236if (args != NULL) {237free(args);238}239if (fd >= 0) {240close(fd);241}242}243244/**245* Read the boottime from /proc/stat.246*/247static long long getBoottime(JNIEnv *env) {248FILE *fp;249char *line = NULL;250size_t len = 0;251long long bootTime = 0;252253fp = fopen("/proc/stat", "r");254if (fp == NULL) {255return -1;256}257258while (getline(&line, &len, fp) != -1) {259if (sscanf(line, "btime %llu", &bootTime) == 1) {260break;261}262}263free(line);264265if (fp != 0) {266fclose(fp);267}268269return bootTime * 1000;270}271272273