Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/os/linux/vm/os_perf_linux.cpp
32285 views
/*1* Copyright (c) 2012, 2018, 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.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "jvm.h"26#include "memory/allocation.inline.hpp"27#include "os_linux.inline.hpp"28#include "runtime/os.hpp"29#include "runtime/os_perf.hpp"3031#ifdef TARGET_ARCH_aarch3232# include "vm_version_ext_aarch32.hpp"33#endif34#ifdef TARGET_ARCH_aarch6435# include "vm_version_ext_aarch64.hpp"36#endif37#ifdef TARGET_ARCH_x8638# include "vm_version_ext_x86.hpp"39#endif40#ifdef TARGET_ARCH_sparc41# include "vm_version_ext_sparc.hpp"42#endif43#ifdef TARGET_ARCH_zero44# include "vm_version_ext_zero.hpp"45#endif46#ifdef TARGET_ARCH_arm47# include "vm_version_ext_arm.hpp"48#endif49#ifdef TARGET_ARCH_ppc50# include "vm_version_ext_ppc.hpp"51#endif5253#include <stdio.h>54#include <stdarg.h>55#include <unistd.h>56#include <errno.h>57#include <string.h>58#include <sys/resource.h>59#include <sys/types.h>60#include <sys/stat.h>61#include <dirent.h>62#include <stdlib.h>63#include <dlfcn.h>64#include <pthread.h>65#include <limits.h>6667#ifdef __ANDROID__68# include "ifaddrs.h"69#else70# include <ifaddrs.h>71#endif72#include <fcntl.h>7374/**75/proc/[number]/stat76Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c.7778The fields, in order, with their proper scanf(3) format specifiers, are:79801. pid %d The process id.81822. comm %s83The filename of the executable, in parentheses. This is visible whether or not the executable is swapped out.84853. state %c86One character from the string "RSDZTW" where R is running, S is sleeping in an interruptible wait, D is waiting in uninterruptible disk87sleep, Z is zombie, T is traced or stopped (on a signal), and W is paging.88894. ppid %d90The PID of the parent.91925. pgrp %d93The process group ID of the process.94956. session %d96The session ID of the process.97987. tty_nr %d99The tty the process uses.1001018. tpgid %d102The process group ID of the process which currently owns the tty that the process is connected to.1031049. flags %lu105The flags of the process. The math bit is decimal 4, and the traced bit is decimal 10.10610710. minflt %lu108The number of minor faults the process has made which have not required loading a memory page from disk.10911011. cminflt %lu111The number of minor faults that the process's waited-for children have made.11211312. majflt %lu114The number of major faults the process has made which have required loading a memory page from disk.11511613. cmajflt %lu117The number of major faults that the process's waited-for children have made.11811914. utime %lu120The number of jiffies that this process has been scheduled in user mode.12112215. stime %lu123The number of jiffies that this process has been scheduled in kernel mode.12412516. cutime %ld126The number of jiffies that this process's waited-for children have been scheduled in user mode. (See also times(2).)12712817. cstime %ld129The number of jiffies that this process' waited-for children have been scheduled in kernel mode.13013118. priority %ld132The standard nice value, plus fifteen. The value is never negative in the kernel.13313419. nice %ld135The nice value ranges from 19 (nicest) to -19 (not nice to others).13613720. 0 %ld This value is hard coded to 0 as a placeholder for a removed field.13813921. itrealvalue %ld140The time in jiffies before the next SIGALRM is sent to the process due to an interval timer.14114222. starttime %lu143The time in jiffies the process started after system boot.14414523. vsize %lu146Virtual memory size in bytes.14714824. rss %ld149Resident Set Size: number of pages the process has in real memory, minus 3 for administrative purposes. This is just the pages which count150towards text, data, or stack space. This does not include pages which have not been demand-loaded in, or which are swapped out.15115225. rlim %lu153Current limit in bytes on the rss of the process (usually 4294967295 on i386).15415526. startcode %lu156The address above which program text can run.15715827. endcode %lu159The address below which program text can run.16016128. startstack %lu162The address of the start of the stack.16316429. kstkesp %lu165The current value of esp (stack pointer), as found in the kernel stack page for the process.16616730. kstkeip %lu168The current EIP (instruction pointer).16917031. signal %lu171The bitmap of pending signals (usually 0).17217332. blocked %lu174The bitmap of blocked signals (usually 0, 2 for shells).17517633. sigignore %lu177The bitmap of ignored signals.17817934. sigcatch %lu180The bitmap of catched signals.18118235. wchan %lu183This is the "channel" in which the process is waiting. It is the address of a system call, and can be looked up in a namelist if you need184a textual name. (If you have an up-to-date /etc/psdatabase, then try ps -l to see the WCHAN field in action.)18518636. nswap %lu187Number of pages swapped - not maintained.18818937. cnswap %lu190Cumulative nswap for child processes.19119238. exit_signal %d193Signal to be sent to parent when we die.19419539. processor %d196CPU number last executed on.197198199200///// SSCANF FORMAT STRING. Copy and use.201202field: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39203format: %d %s %c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld %ld %ld %ld %lu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %d %d204205206*/207208/**209* For platforms that have them, when declaring210* a printf-style function,211* formatSpec is the parameter number (starting at 1)212* that is the format argument ("%d pid %s")213* params is the parameter number where the actual args to214* the format starts. If the args are in a va_list, this215* should be 0.216*/217#ifndef PRINTF_ARGS218# define PRINTF_ARGS(formatSpec, params) ATTRIBUTE_PRINTF(formatSpec, params)219#endif220221#ifndef SCANF_ARGS222# define SCANF_ARGS(formatSpec, params) ATTRIBUTE_SCANF(formatSpec, params)223#endif224225#ifndef _PRINTFMT_226# define _PRINTFMT_227#endif228229#ifndef _SCANFMT_230# define _SCANFMT_231#endif232233234struct CPUPerfTicks {235uint64_t used;236uint64_t usedKernel;237uint64_t total;238};239240typedef enum {241CPU_LOAD_VM_ONLY,242CPU_LOAD_GLOBAL,243} CpuLoadTarget;244245enum {246UNDETECTED,247UNDETECTABLE,248LINUX26_NPTL,249BAREMETAL250};251252struct CPUPerfCounters {253int nProcs;254CPUPerfTicks jvmTicks;255CPUPerfTicks* cpus;256};257258static double get_cpu_load(int which_logical_cpu, CPUPerfCounters* counters, double* pkernelLoad, CpuLoadTarget target);259260/** reads /proc/<pid>/stat data, with some checks and some skips.261* Ensure that 'fmt' does _NOT_ contain the first two "%d %s"262*/263static int SCANF_ARGS(2, 0) vread_statdata(const char* procfile, _SCANFMT_ const char* fmt, va_list args) {264FILE*f;265int n;266char buf[2048];267268if ((f = fopen(procfile, "r")) == NULL) {269return -1;270}271272if ((n = fread(buf, 1, sizeof(buf), f)) != -1) {273char *tmp;274275buf[n-1] = '\0';276/** skip through pid and exec name. */277if ((tmp = strrchr(buf, ')')) != NULL) {278// skip the ')' and the following space279// but check that buffer is long enough280tmp += 2;281if (tmp < buf + n) {282n = vsscanf(tmp, fmt, args);283}284}285}286287fclose(f);288289return n;290}291292static int SCANF_ARGS(2, 3) read_statdata(const char* procfile, _SCANFMT_ const char* fmt, ...) {293int n;294va_list args;295296va_start(args, fmt);297n = vread_statdata(procfile, fmt, args);298va_end(args);299return n;300}301302static FILE* open_statfile(void) {303FILE *f;304305if ((f = fopen("/proc/stat", "r")) == NULL) {306static int haveWarned = 0;307if (!haveWarned) {308haveWarned = 1;309}310}311return f;312}313314static void315next_line(FILE *f) {316int c;317do {318c = fgetc(f);319} while (c != '\n' && c != EOF);320}321322/**323* Return the total number of ticks since the system was booted.324* If the usedTicks parameter is not NULL, it will be filled with325* the number of ticks spent on actual processes (user, system or326* nice processes) since system boot. Note that this is the total number327* of "executed" ticks on _all_ CPU:s, that is on a n-way system it is328* n times the number of ticks that has passed in clock time.329*330* Returns a negative value if the reading of the ticks failed.331*/332static OSReturn get_total_ticks(int which_logical_cpu, CPUPerfTicks* pticks) {333FILE* fh;334uint64_t userTicks, niceTicks, systemTicks, idleTicks;335uint64_t iowTicks = 0, irqTicks = 0, sirqTicks= 0;336int logical_cpu = -1;337const int expected_assign_count = (-1 == which_logical_cpu) ? 4 : 5;338int n;339340if ((fh = open_statfile()) == NULL) {341return OS_ERR;342}343if (-1 == which_logical_cpu) {344n = fscanf(fh, "cpu " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "345UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT,346&userTicks, &niceTicks, &systemTicks, &idleTicks,347&iowTicks, &irqTicks, &sirqTicks);348} else {349// Move to next line350next_line(fh);351352// find the line for requested cpu faster to just iterate linefeeds?353for (int i = 0; i < which_logical_cpu; i++) {354next_line(fh);355}356357n = fscanf(fh, "cpu%u " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "358UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT,359&logical_cpu, &userTicks, &niceTicks,360&systemTicks, &idleTicks, &iowTicks, &irqTicks, &sirqTicks);361}362363fclose(fh);364if (n < expected_assign_count || logical_cpu != which_logical_cpu) {365#ifdef DEBUG_LINUX_PROC_STAT366vm_fprintf(stderr, "[stat] read failed");367#endif368return OS_ERR;369}370371#ifdef DEBUG_LINUX_PROC_STAT372vm_fprintf(stderr, "[stat] read "373UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " "374UINT64_FORMAT " " UINT64_FORMAT " " UINT64_FORMAT " \n",375userTicks, niceTicks, systemTicks, idleTicks,376iowTicks, irqTicks, sirqTicks);377#endif378379pticks->used = userTicks + niceTicks;380pticks->usedKernel = systemTicks + irqTicks + sirqTicks;381pticks->total = userTicks + niceTicks + systemTicks + idleTicks +382iowTicks + irqTicks + sirqTicks;383384return OS_OK;385}386387388static int get_systemtype(void) {389static int procEntriesType = UNDETECTED;390DIR *taskDir;391392if (procEntriesType != UNDETECTED) {393return procEntriesType;394}395396// Check whether we have a task subdirectory397if ((taskDir = opendir("/proc/self/task")) == NULL) {398procEntriesType = UNDETECTABLE;399} else {400// The task subdirectory exists; we're on a Linux >= 2.6 system401closedir(taskDir);402procEntriesType = LINUX26_NPTL;403}404405return procEntriesType;406}407408/** read user and system ticks from a named procfile, assumed to be in 'stat' format then. */409static int read_ticks(const char* procfile, uint64_t* userTicks, uint64_t* systemTicks) {410return read_statdata(procfile, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u " UINT64_FORMAT " " UINT64_FORMAT,411userTicks, systemTicks);412}413414/**415* Return the number of ticks spent in any of the processes belonging416* to the JVM on any CPU.417*/418static OSReturn get_jvm_ticks(CPUPerfTicks* pticks) {419uint64_t userTicks;420uint64_t systemTicks;421422if (get_systemtype() != LINUX26_NPTL) {423return OS_ERR;424}425426if (read_ticks("/proc/self/stat", &userTicks, &systemTicks) != 2) {427return OS_ERR;428}429430// get the total431if (get_total_ticks(-1, pticks) != OS_OK) {432return OS_ERR;433}434435pticks->used = userTicks;436pticks->usedKernel = systemTicks;437438return OS_OK;439}440441/**442* Return the load of the CPU as a double. 1.0 means the CPU process uses all443* available time for user or system processes, 0.0 means the CPU uses all time444* being idle.445*446* Returns a negative value if there is a problem in determining the CPU load.447*/448static double get_cpu_load(int which_logical_cpu, CPUPerfCounters* counters, double* pkernelLoad, CpuLoadTarget target) {449uint64_t udiff, kdiff, tdiff;450CPUPerfTicks* pticks;451CPUPerfTicks tmp;452double user_load;453454*pkernelLoad = 0.0;455456if (target == CPU_LOAD_VM_ONLY) {457pticks = &counters->jvmTicks;458} else if (-1 == which_logical_cpu) {459pticks = &counters->cpus[counters->nProcs];460} else {461pticks = &counters->cpus[which_logical_cpu];462}463464tmp = *pticks;465466if (target == CPU_LOAD_VM_ONLY) {467if (get_jvm_ticks(pticks) != OS_OK) {468return -1.0;469}470} else if (get_total_ticks(which_logical_cpu, pticks) != OS_OK) {471return -1.0;472}473474// seems like we sometimes end up with less kernel ticks when475// reading /proc/self/stat a second time, timing issue between cpus?476if (pticks->usedKernel < tmp.usedKernel) {477kdiff = 0;478} else {479kdiff = pticks->usedKernel - tmp.usedKernel;480}481tdiff = pticks->total - tmp.total;482udiff = pticks->used - tmp.used;483484if (tdiff == 0) {485return 0.0;486} else if (tdiff < (udiff + kdiff)) {487tdiff = udiff + kdiff;488}489*pkernelLoad = (kdiff / (double)tdiff);490// BUG9044876, normalize return values to sane values491*pkernelLoad = MAX2<double>(*pkernelLoad, 0.0);492*pkernelLoad = MIN2<double>(*pkernelLoad, 1.0);493494user_load = (udiff / (double)tdiff);495user_load = MAX2<double>(user_load, 0.0);496user_load = MIN2<double>(user_load, 1.0);497498return user_load;499}500501static int SCANF_ARGS(1, 2) parse_stat(_SCANFMT_ const char* fmt, ...) {502FILE *f;503va_list args;504505va_start(args, fmt);506507if ((f = open_statfile()) == NULL) {508va_end(args);509return OS_ERR;510}511for (;;) {512char line[80];513if (fgets(line, sizeof(line), f) != NULL) {514if (vsscanf(line, fmt, args) == 1) {515fclose(f);516va_end(args);517return OS_OK;518}519} else {520fclose(f);521va_end(args);522return OS_ERR;523}524}525}526527static int get_noof_context_switches(uint64_t* switches) {528return parse_stat("ctxt " UINT64_FORMAT "\n", switches);529}530531/** returns boot time in _seconds_ since epoch */532static int get_boot_time(uint64_t* time) {533return parse_stat("btime " UINT64_FORMAT "\n", time);534}535536static int perf_context_switch_rate(double* rate) {537static pthread_mutex_t contextSwitchLock = PTHREAD_MUTEX_INITIALIZER;538static uint64_t lastTime;539static uint64_t lastSwitches;540static double lastRate;541542uint64_t lt = 0;543int res = 0;544545if (lastTime == 0) {546uint64_t tmp;547if (get_boot_time(&tmp) < 0) {548return OS_ERR;549}550lt = tmp * 1000;551}552553res = OS_OK;554555pthread_mutex_lock(&contextSwitchLock);556{557558uint64_t sw;559s8 t, d;560561if (lastTime == 0) {562lastTime = lt;563}564565t = os::javaTimeMillis();566d = t - lastTime;567568if (d == 0) {569*rate = lastRate;570} else if (!get_noof_context_switches(&sw)) {571*rate = ( (double)(sw - lastSwitches) / d ) * 1000;572lastRate = *rate;573lastSwitches = sw;574lastTime = t;575} else {576*rate = 0;577res = OS_ERR;578}579if (*rate <= 0) {580*rate = 0;581lastRate = 0;582}583}584pthread_mutex_unlock(&contextSwitchLock);585586return res;587}588589class CPUPerformanceInterface::CPUPerformance : public CHeapObj<mtInternal> {590friend class CPUPerformanceInterface;591private:592CPUPerfCounters _counters;593594int cpu_load(int which_logical_cpu, double* cpu_load);595int context_switch_rate(double* rate);596int cpu_load_total_process(double* cpu_load);597int cpu_loads_process(double* pjvmUserLoad, double* pjvmKernelLoad, double* psystemTotalLoad);598599public:600CPUPerformance();601bool initialize();602~CPUPerformance();603};604605CPUPerformanceInterface::CPUPerformance::CPUPerformance() {606_counters.nProcs = os::active_processor_count();607_counters.cpus = NULL;608}609610bool CPUPerformanceInterface::CPUPerformance::initialize() {611size_t tick_array_size = (_counters.nProcs +1) * sizeof(CPUPerfTicks);612_counters.cpus = (CPUPerfTicks*)NEW_C_HEAP_ARRAY(char, tick_array_size, mtInternal);613if (NULL == _counters.cpus) {614return false;615}616memset(_counters.cpus, 0, tick_array_size);617618// For the CPU load total619get_total_ticks(-1, &_counters.cpus[_counters.nProcs]);620621// For each CPU622for (int i = 0; i < _counters.nProcs; i++) {623get_total_ticks(i, &_counters.cpus[i]);624}625// For JVM load626get_jvm_ticks(&_counters.jvmTicks);627628// initialize context switch system629// the double is only for init630double init_ctx_switch_rate;631perf_context_switch_rate(&init_ctx_switch_rate);632633return true;634}635636CPUPerformanceInterface::CPUPerformance::~CPUPerformance() {637if (_counters.cpus != NULL) {638FREE_C_HEAP_ARRAY(char, _counters.cpus, mtInternal);639}640}641642int CPUPerformanceInterface::CPUPerformance::cpu_load(int which_logical_cpu, double* cpu_load) {643double u, s;644u = get_cpu_load(which_logical_cpu, &_counters, &s, CPU_LOAD_GLOBAL);645if (u < 0) {646*cpu_load = 0.0;647return OS_ERR;648}649// Cap total systemload to 1.0650*cpu_load = MIN2<double>((u + s), 1.0);651return OS_OK;652}653654int CPUPerformanceInterface::CPUPerformance::cpu_load_total_process(double* cpu_load) {655double u, s;656u = get_cpu_load(-1, &_counters, &s, CPU_LOAD_VM_ONLY);657if (u < 0) {658*cpu_load = 0.0;659return OS_ERR;660}661*cpu_load = u + s;662return OS_OK;663}664665int CPUPerformanceInterface::CPUPerformance::cpu_loads_process(double* pjvmUserLoad, double* pjvmKernelLoad, double* psystemTotalLoad) {666double u, s, t;667668assert(pjvmUserLoad != NULL, "pjvmUserLoad not inited");669assert(pjvmKernelLoad != NULL, "pjvmKernelLoad not inited");670assert(psystemTotalLoad != NULL, "psystemTotalLoad not inited");671672u = get_cpu_load(-1, &_counters, &s, CPU_LOAD_VM_ONLY);673if (u < 0) {674*pjvmUserLoad = 0.0;675*pjvmKernelLoad = 0.0;676*psystemTotalLoad = 0.0;677return OS_ERR;678}679680cpu_load(-1, &t);681// clamp at user+system and 1.0682if (u + s > t) {683t = MIN2<double>(u + s, 1.0);684}685686*pjvmUserLoad = u;687*pjvmKernelLoad = s;688*psystemTotalLoad = t;689690return OS_OK;691}692693int CPUPerformanceInterface::CPUPerformance::context_switch_rate(double* rate) {694return perf_context_switch_rate(rate);695}696697CPUPerformanceInterface::CPUPerformanceInterface() {698_impl = NULL;699}700701bool CPUPerformanceInterface::initialize() {702_impl = new CPUPerformanceInterface::CPUPerformance();703return NULL == _impl ? false : _impl->initialize();704}705706CPUPerformanceInterface::~CPUPerformanceInterface() {707if (_impl != NULL) {708delete _impl;709}710}711712int CPUPerformanceInterface::cpu_load(int which_logical_cpu, double* cpu_load) const {713return _impl->cpu_load(which_logical_cpu, cpu_load);714}715716int CPUPerformanceInterface::cpu_load_total_process(double* cpu_load) const {717return _impl->cpu_load_total_process(cpu_load);718}719720int CPUPerformanceInterface::cpu_loads_process(double* pjvmUserLoad, double* pjvmKernelLoad, double* psystemTotalLoad) const {721return _impl->cpu_loads_process(pjvmUserLoad, pjvmKernelLoad, psystemTotalLoad);722}723724int CPUPerformanceInterface::context_switch_rate(double* rate) const {725return _impl->context_switch_rate(rate);726}727728class SystemProcessInterface::SystemProcesses : public CHeapObj<mtInternal> {729friend class SystemProcessInterface;730private:731class ProcessIterator : public CHeapObj<mtInternal> {732friend class SystemProcessInterface::SystemProcesses;733private:734DIR* _dir;735struct dirent* _entry;736bool _valid;737char _exeName[PATH_MAX];738char _exePath[PATH_MAX];739740ProcessIterator();741~ProcessIterator();742bool initialize();743744bool is_valid() const { return _valid; }745bool is_valid_entry(struct dirent* entry) const;746bool is_dir(const char* name) const;747int fsize(const char* name, uint64_t& size) const;748749char* allocate_string(const char* str) const;750void get_exe_name();751char* get_exe_path();752char* get_cmdline();753754int current(SystemProcess* process_info);755int next_process();756};757758ProcessIterator* _iterator;759SystemProcesses();760bool initialize();761~SystemProcesses();762763//information about system processes764int system_processes(SystemProcess** system_processes, int* no_of_sys_processes) const;765};766767bool SystemProcessInterface::SystemProcesses::ProcessIterator::is_dir(const char* name) const {768struct stat mystat;769int ret_val = 0;770771ret_val = stat(name, &mystat);772if (ret_val < 0) {773return false;774}775ret_val = S_ISDIR(mystat.st_mode);776return ret_val > 0;777}778779int SystemProcessInterface::SystemProcesses::ProcessIterator::fsize(const char* name, uint64_t& size) const {780assert(name != NULL, "name pointer is NULL!");781size = 0;782struct stat fbuf;783784if (stat(name, &fbuf) < 0) {785return OS_ERR;786}787size = fbuf.st_size;788return OS_OK;789}790791// if it has a numeric name, is a directory and has a 'stat' file in it792bool SystemProcessInterface::SystemProcesses::ProcessIterator::is_valid_entry(struct dirent* entry) const {793char buffer[PATH_MAX];794uint64_t size = 0;795796if (atoi(entry->d_name) != 0) {797jio_snprintf(buffer, PATH_MAX, "/proc/%s", entry->d_name);798buffer[PATH_MAX - 1] = '\0';799800if (is_dir(buffer)) {801jio_snprintf(buffer, PATH_MAX, "/proc/%s/stat", entry->d_name);802buffer[PATH_MAX - 1] = '\0';803if (fsize(buffer, size) != OS_ERR) {804return true;805}806}807}808return false;809}810811// get exe-name from /proc/<pid>/stat812void SystemProcessInterface::SystemProcesses::ProcessIterator::get_exe_name() {813FILE* fp;814char buffer[PATH_MAX];815816jio_snprintf(buffer, PATH_MAX, "/proc/%s/stat", _entry->d_name);817buffer[PATH_MAX - 1] = '\0';818if ((fp = fopen(buffer, "r")) != NULL) {819if (fgets(buffer, PATH_MAX, fp) != NULL) {820char* start, *end;821// exe-name is between the first pair of ( and )822start = strchr(buffer, '(');823if (start != NULL && start[1] != '\0') {824start++;825end = strrchr(start, ')');826if (end != NULL) {827size_t len;828len = MIN2<size_t>(end - start, sizeof(_exeName) - 1);829memcpy(_exeName, start, len);830_exeName[len] = '\0';831}832}833}834fclose(fp);835}836}837838// get command line from /proc/<pid>/cmdline839char* SystemProcessInterface::SystemProcesses::ProcessIterator::get_cmdline() {840FILE* fp;841char buffer[PATH_MAX];842char* cmdline = NULL;843844jio_snprintf(buffer, PATH_MAX, "/proc/%s/cmdline", _entry->d_name);845buffer[PATH_MAX - 1] = '\0';846if ((fp = fopen(buffer, "r")) != NULL) {847size_t size = 0;848char dummy;849850// find out how long the file is (stat always returns 0)851while (fread(&dummy, 1, 1, fp) == 1) {852size++;853}854if (size > 0) {855cmdline = NEW_C_HEAP_ARRAY(char, size + 1, mtInternal);856if (cmdline != NULL) {857cmdline[0] = '\0';858if (fseek(fp, 0, SEEK_SET) == 0) {859if (fread(cmdline, 1, size, fp) == size) {860// the file has the arguments separated by '\0',861// so we translate '\0' to ' '862for (size_t i = 0; i < size; i++) {863if (cmdline[i] == '\0') {864cmdline[i] = ' ';865}866}867cmdline[size] = '\0';868}869}870}871}872fclose(fp);873}874return cmdline;875}876877// get full path to exe from /proc/<pid>/exe symlink878char* SystemProcessInterface::SystemProcesses::ProcessIterator::get_exe_path() {879char buffer[PATH_MAX];880881jio_snprintf(buffer, PATH_MAX, "/proc/%s/exe", _entry->d_name);882buffer[PATH_MAX - 1] = '\0';883return realpath(buffer, _exePath);884}885886char* SystemProcessInterface::SystemProcesses::ProcessIterator::allocate_string(const char* str) const {887if (str != NULL) {888size_t len = strlen(str);889char* tmp = NEW_C_HEAP_ARRAY(char, len+1, mtInternal);890strncpy(tmp, str, len);891tmp[len] = '\0';892return tmp;893}894return NULL;895}896897int SystemProcessInterface::SystemProcesses::ProcessIterator::current(SystemProcess* process_info) {898if (!is_valid()) {899return OS_ERR;900}901902process_info->set_pid(atoi(_entry->d_name));903904get_exe_name();905process_info->set_name(allocate_string(_exeName));906907if (get_exe_path() != NULL) {908process_info->set_path(allocate_string(_exePath));909}910911char* cmdline = NULL;912cmdline = get_cmdline();913if (cmdline != NULL) {914process_info->set_command_line(allocate_string(cmdline));915FREE_C_HEAP_ARRAY(char, cmdline, mtInternal);916}917918return OS_OK;919}920921int SystemProcessInterface::SystemProcesses::ProcessIterator::next_process() {922if (!is_valid()) {923return OS_ERR;924}925926do {927_entry = os::readdir(_dir);928if (_entry == NULL) {929// Error or reached end. Could use errno to distinguish those cases.930_valid = false;931return OS_ERR;932}933} while(!is_valid_entry(_entry));934935_valid = true;936return OS_OK;937}938939SystemProcessInterface::SystemProcesses::ProcessIterator::ProcessIterator() {940_dir = NULL;941_entry = NULL;942_valid = false;943}944945bool SystemProcessInterface::SystemProcesses::ProcessIterator::initialize() {946_dir = os::opendir("/proc");947_entry = NULL;948_valid = true;949next_process();950951return true;952}953954SystemProcessInterface::SystemProcesses::ProcessIterator::~ProcessIterator() {955if (_dir != NULL) {956os::closedir(_dir);957}958}959960SystemProcessInterface::SystemProcesses::SystemProcesses() {961_iterator = NULL;962}963964bool SystemProcessInterface::SystemProcesses::initialize() {965_iterator = new SystemProcessInterface::SystemProcesses::ProcessIterator();966return NULL == _iterator ? false : _iterator->initialize();967}968969SystemProcessInterface::SystemProcesses::~SystemProcesses() {970if (_iterator != NULL) {971delete _iterator;972}973}974975int SystemProcessInterface::SystemProcesses::system_processes(SystemProcess** system_processes, int* no_of_sys_processes) const {976assert(system_processes != NULL, "system_processes pointer is NULL!");977assert(no_of_sys_processes != NULL, "system_processes counter pointers is NULL!");978assert(_iterator != NULL, "iterator is NULL!");979980// initialize pointers981*no_of_sys_processes = 0;982*system_processes = NULL;983984while (_iterator->is_valid()) {985SystemProcess* tmp = new SystemProcess();986_iterator->current(tmp);987988//if already existing head989if (*system_processes != NULL) {990//move "first to second"991tmp->set_next(*system_processes);992}993// new head994*system_processes = tmp;995// increment996(*no_of_sys_processes)++;997// step forward998_iterator->next_process();999}1000return OS_OK;1001}10021003int SystemProcessInterface::system_processes(SystemProcess** system_procs, int* no_of_sys_processes) const {1004return _impl->system_processes(system_procs, no_of_sys_processes);1005}10061007SystemProcessInterface::SystemProcessInterface() {1008_impl = NULL;1009}10101011bool SystemProcessInterface::initialize() {1012_impl = new SystemProcessInterface::SystemProcesses();1013return NULL == _impl ? false : _impl->initialize();1014}10151016SystemProcessInterface::~SystemProcessInterface() {1017if (_impl != NULL) {1018delete _impl;1019}1020}10211022CPUInformationInterface::CPUInformationInterface() {1023_cpu_info = NULL;1024}10251026bool CPUInformationInterface::initialize() {1027_cpu_info = new CPUInformation();1028if (NULL == _cpu_info) {1029return false;1030}1031_cpu_info->set_number_of_hardware_threads(VM_Version_Ext::number_of_threads());1032_cpu_info->set_number_of_cores(VM_Version_Ext::number_of_cores());1033_cpu_info->set_number_of_sockets(VM_Version_Ext::number_of_sockets());1034_cpu_info->set_cpu_name(VM_Version_Ext::cpu_name());1035_cpu_info->set_cpu_description(VM_Version_Ext::cpu_description());10361037return true;1038}10391040CPUInformationInterface::~CPUInformationInterface() {1041if (_cpu_info != NULL) {1042if (_cpu_info->cpu_name() != NULL) {1043const char* cpu_name = _cpu_info->cpu_name();1044FREE_C_HEAP_ARRAY(char, cpu_name, mtInternal);1045_cpu_info->set_cpu_name(NULL);1046}1047if (_cpu_info->cpu_description() != NULL) {1048const char* cpu_desc = _cpu_info->cpu_description();1049FREE_C_HEAP_ARRAY(char, cpu_desc, mtInternal);1050_cpu_info->set_cpu_description(NULL);1051}1052delete _cpu_info;1053}1054}10551056int CPUInformationInterface::cpu_information(CPUInformation& cpu_info) {1057if (_cpu_info == NULL) {1058return OS_ERR;1059}10601061cpu_info = *_cpu_info; // shallow copy assignment1062return OS_OK;1063}10641065class NetworkPerformanceInterface::NetworkPerformance : public CHeapObj<mtInternal> {1066friend class NetworkPerformanceInterface;1067private:1068NetworkPerformance();1069NetworkPerformance(const NetworkPerformance& rhs); // no impl1070NetworkPerformance& operator=(const NetworkPerformance& rhs); // no impl1071bool initialize();1072~NetworkPerformance();1073int64_t read_counter(const char* iface, const char* counter) const;1074int network_utilization(NetworkInterface** network_interfaces) const;1075};10761077NetworkPerformanceInterface::NetworkPerformance::NetworkPerformance() {10781079}10801081bool NetworkPerformanceInterface::NetworkPerformance::initialize() {1082return true;1083}10841085NetworkPerformanceInterface::NetworkPerformance::~NetworkPerformance() {1086}10871088int64_t NetworkPerformanceInterface::NetworkPerformance::read_counter(const char* iface, const char* counter) const {1089char buf[128];10901091snprintf(buf, sizeof(buf), "/sys/class/net/%s/statistics/%s", iface, counter);10921093int fd = open(buf, O_RDONLY);1094if (fd == -1) {1095return -1;1096}10971098ssize_t num_bytes = read(fd, buf, sizeof(buf));1099close(fd);1100if ((num_bytes == -1) || (num_bytes >= static_cast<ssize_t>(sizeof(buf))) || (num_bytes < 1)) {1101return -1;1102}11031104buf[num_bytes] = '\0';1105int64_t value = strtoll(buf, NULL, 10);11061107return value;1108}11091110int NetworkPerformanceInterface::NetworkPerformance::network_utilization(NetworkInterface** network_interfaces) const1111{1112ifaddrs* addresses;1113ifaddrs* cur_address;11141115if (getifaddrs(&addresses) != 0) {1116return OS_ERR;1117}11181119NetworkInterface* ret = NULL;1120for (cur_address = addresses; cur_address != NULL; cur_address = cur_address->ifa_next) {1121if ((cur_address->ifa_addr == NULL) || (cur_address->ifa_addr->sa_family != AF_PACKET)) {1122continue;1123}11241125int64_t bytes_in = read_counter(cur_address->ifa_name, "rx_bytes");1126int64_t bytes_out = read_counter(cur_address->ifa_name, "tx_bytes");11271128NetworkInterface* cur = new NetworkInterface(cur_address->ifa_name, bytes_in, bytes_out, ret);1129ret = cur;1130}11311132freeifaddrs(addresses);1133*network_interfaces = ret;11341135return OS_OK;1136}11371138NetworkPerformanceInterface::NetworkPerformanceInterface() {1139_impl = NULL;1140}11411142NetworkPerformanceInterface::~NetworkPerformanceInterface() {1143if (_impl != NULL) {1144delete _impl;1145}1146}11471148bool NetworkPerformanceInterface::initialize() {1149_impl = new NetworkPerformanceInterface::NetworkPerformance();1150return _impl != NULL && _impl->initialize();1151}11521153int NetworkPerformanceInterface::network_utilization(NetworkInterface** network_interfaces) const {1154return _impl->network_utilization(network_interfaces);1155}115611571158