1 /*
2 * Copyright (c) 2012, 2020, 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.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "jvm.h"
27 #include "memory/allocation.inline.hpp"
28 #include "os_aix.inline.hpp"
29 #include "runtime/os.hpp"
30 #include "runtime/os_perf.hpp"
31 #include "utilities/globalDefinitions.hpp"
32
33 #include CPU_HEADER(vm_version_ext)
34
35 #include <stdio.h>
36 #include <stdarg.h>
37 #include <unistd.h>
38 #include <errno.h>
39 #include <string.h>
40 #include <sys/resource.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <dirent.h>
44 #include <stdlib.h>
45 #include <dlfcn.h>
46 #include <pthread.h>
47 #include <limits.h>
48
49 /**
50 /proc/[number]/stat
51 Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c.
52
53 The fields, in order, with their proper scanf(3) format specifiers, are:
54
55 1. pid %d The process id.
56
57 2. comm %s
58 The filename of the executable, in parentheses. This is visible whether or not the executable is swapped out.
59
60 3. state %c
61 One character from the string "RSDZTW" where R is running, S is sleeping in an interruptible wait, D is waiting in uninterruptible disk
62 sleep, Z is zombie, T is traced or stopped (on a signal), and W is paging.
63
64 4. ppid %d
65 The PID of the parent.
66
67 5. pgrp %d
68 The process group ID of the process.
69
70 6. session %d
71 The session ID of the process.
72
73 7. tty_nr %d
74 The tty the process uses.
75
76 8. tpgid %d
77 The process group ID of the process which currently owns the tty that the process is connected to.
78
79 9. flags %lu
80 The flags of the process. The math bit is decimal 4, and the traced bit is decimal 10.
81
82 10. minflt %lu
83 The number of minor faults the process has made which have not required loading a memory page from disk.
84
85 11. cminflt %lu
86 The number of minor faults that the process's waited-for children have made.
87
88 12. majflt %lu
89 The number of major faults the process has made which have required loading a memory page from disk.
90
91 13. cmajflt %lu
92 The number of major faults that the process's waited-for children have made.
93
94 14. utime %lu
95 The number of jiffies that this process has been scheduled in user mode.
96
97 15. stime %lu
98 The number of jiffies that this process has been scheduled in kernel mode.
99
100 16. cutime %ld
101 The number of jiffies that this process's waited-for children have been scheduled in user mode. (See also times(2).)
102
103 17. cstime %ld
104 The number of jiffies that this process' waited-for children have been scheduled in kernel mode.
105
106 18. priority %ld
107 The standard nice value, plus fifteen. The value is never negative in the kernel.
108
109 19. nice %ld
110 The nice value ranges from 19 (nicest) to -19 (not nice to others).
111
112 20. 0 %ld This value is hard coded to 0 as a placeholder for a removed field.
113
114 21. itrealvalue %ld
115 The time in jiffies before the next SIGALRM is sent to the process due to an interval timer.
116
117 22. starttime %lu
118 The time in jiffies the process started after system boot.
119
120 23. vsize %lu
121 Virtual memory size in bytes.
122
123 24. rss %ld
124 Resident Set Size: number of pages the process has in real memory, minus 3 for administrative purposes. This is just the pages which count
125 towards text, data, or stack space. This does not include pages which have not been demand-loaded in, or which are swapped out.
126
127 25. rlim %lu
128 Current limit in bytes on the rss of the process (usually 4294967295 on i386).
129
130 26. startcode %lu
131 The address above which program text can run.
132
133 27. endcode %lu
134 The address below which program text can run.
135
136 28. startstack %lu
137 The address of the start of the stack.
138
139 29. kstkesp %lu
140 The current value of esp (stack pointer), as found in the kernel stack page for the process.
141
142 30. kstkeip %lu
143 The current EIP (instruction pointer).
144
145 31. signal %lu
146 The bitmap of pending signals (usually 0).
147
148 32. blocked %lu
149 The bitmap of blocked signals (usually 0, 2 for shells).
150
151 33. sigignore %lu
152 The bitmap of ignored signals.
153
154 34. sigcatch %lu
155 The bitmap of catched signals.
156
157 35. wchan %lu
158 This 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 need
159 a textual name. (If you have an up-to-date /etc/psdatabase, then try ps -l to see the WCHAN field in action.)
160
161 36. nswap %lu
162 Number of pages swapped - not maintained.
163
164 37. cnswap %lu
165 Cumulative nswap for child processes.
166
167 38. exit_signal %d
168 Signal to be sent to parent when we die.
169
170 39. processor %d
171 CPU number last executed on.
172
173
174
175 ///// SSCANF FORMAT STRING. Copy and use.
176
177 field: 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 39
178 format: %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 %d
179
180
181 */
182
183 /**
184 * For platforms that have them, when declaring
185 * a printf-style function,
186 * formatSpec is the parameter number (starting at 1)
187 * that is the format argument ("%d pid %s")
188 * params is the parameter number where the actual args to
189 * the format starts. If the args are in a va_list, this
190 * should be 0.
191 */
192 #ifndef PRINTF_ARGS
193 # define PRINTF_ARGS(formatSpec, params) ATTRIBUTE_PRINTF(formatSpec, params)
194 #endif
195
196 #ifndef SCANF_ARGS
197 # define SCANF_ARGS(formatSpec, params) ATTRIBUTE_SCANF(formatSpec, params)
198 #endif
199
200 #ifndef _PRINTFMT_
201 # define _PRINTFMT_
202 #endif
203
204 #ifndef _SCANFMT_
205 # define _SCANFMT_
206 #endif
207
208
209 struct CPUPerfTicks {
210 uint64_t used;
211 uint64_t usedKernel;
212 uint64_t total;
213 };
214
215 typedef enum {
216 CPU_LOAD_VM_ONLY,
217 CPU_LOAD_GLOBAL,
218 } CpuLoadTarget;
219
220 enum {
221 UNDETECTED,
222 UNDETECTABLE,
223 LINUX26_NPTL,
224 BAREMETAL
225 };
226
227 struct CPUPerfCounters {
228 int nProcs;
229 CPUPerfTicks jvmTicks;
230 CPUPerfTicks* cpus;
231 };
232
233 static double get_cpu_load(int which_logical_cpu, CPUPerfCounters* counters, double* pkernelLoad, CpuLoadTarget target);
234
235 /** reads /proc/<pid>/stat data, with some checks and some skips.
236 * Ensure that 'fmt' does _NOT_ contain the first two "%d %s"
237 */
vread_statdata(const char * procfile,_SCANFMT_ const char * fmt,va_list args)238 static int SCANF_ARGS(2, 0) vread_statdata(const char* procfile, _SCANFMT_ const char* fmt, va_list args) {
239 FILE*f;
240 int n;
241 char buf[2048];
242
243 if ((f = fopen(procfile, "r")) == NULL) {
244 return -1;
245 }
246
247 if ((n = fread(buf, 1, sizeof(buf), f)) != -1) {
248 char *tmp;
249
250 buf[n-1] = '\0';
251 /** skip through pid and exec name. */
252 if ((tmp = strrchr(buf, ')')) != NULL) {
253 // skip the ')' and the following space
254 // but check that buffer is long enough
255 tmp += 2;
256 if (tmp < buf + n) {
257 n = vsscanf(tmp, fmt, args);
258 }
259 }
260 }
261
262 fclose(f);
263
264 return n;
265 }
266
read_statdata(const char * procfile,_SCANFMT_ const char * fmt,...)267 static int SCANF_ARGS(2, 3) read_statdata(const char* procfile, _SCANFMT_ const char* fmt, ...) {
268 int n;
269 va_list args;
270
271 va_start(args, fmt);
272 n = vread_statdata(procfile, fmt, args);
273 va_end(args);
274 return n;
275 }
276
277 /**
278 * on Linux we got the ticks related information from /proc/stat
279 * this does not work on AIX, libperfstat might be an alternative
280 */
get_total_ticks(int which_logical_cpu,CPUPerfTicks * pticks)281 static OSReturn get_total_ticks(int which_logical_cpu, CPUPerfTicks* pticks) {
282 return OS_ERR;
283 }
284
285 /** read user and system ticks from a named procfile, assumed to be in 'stat' format then. */
read_ticks(const char * procfile,uint64_t * userTicks,uint64_t * systemTicks)286 static int read_ticks(const char* procfile, uint64_t* userTicks, uint64_t* systemTicks) {
287 return read_statdata(procfile, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u " UINT64_FORMAT " " UINT64_FORMAT,
288 userTicks, systemTicks);
289 }
290
291 /**
292 * Return the number of ticks spent in any of the processes belonging
293 * to the JVM on any CPU.
294 */
get_jvm_ticks(CPUPerfTicks * pticks)295 static OSReturn get_jvm_ticks(CPUPerfTicks* pticks) {
296 return OS_ERR;
297 }
298
299 /**
300 * Return the load of the CPU as a double. 1.0 means the CPU process uses all
301 * available time for user or system processes, 0.0 means the CPU uses all time
302 * being idle.
303 *
304 * Returns a negative value if there is a problem in determining the CPU load.
305 */
get_cpu_load(int which_logical_cpu,CPUPerfCounters * counters,double * pkernelLoad,CpuLoadTarget target)306 static double get_cpu_load(int which_logical_cpu, CPUPerfCounters* counters, double* pkernelLoad, CpuLoadTarget target) {
307 uint64_t udiff, kdiff, tdiff;
308 CPUPerfTicks* pticks;
309 CPUPerfTicks tmp;
310 double user_load;
311
312 *pkernelLoad = 0.0;
313
314 if (target == CPU_LOAD_VM_ONLY) {
315 pticks = &counters->jvmTicks;
316 } else if (-1 == which_logical_cpu) {
317 pticks = &counters->cpus[counters->nProcs];
318 } else {
319 pticks = &counters->cpus[which_logical_cpu];
320 }
321
322 tmp = *pticks;
323
324 if (target == CPU_LOAD_VM_ONLY) {
325 if (get_jvm_ticks(pticks) != OS_OK) {
326 return -1.0;
327 }
328 } else if (get_total_ticks(which_logical_cpu, pticks) != OS_OK) {
329 return -1.0;
330 }
331
332 // seems like we sometimes end up with less kernel ticks when
333 // reading /proc/self/stat a second time, timing issue between cpus?
334 if (pticks->usedKernel < tmp.usedKernel) {
335 kdiff = 0;
336 } else {
337 kdiff = pticks->usedKernel - tmp.usedKernel;
338 }
339 tdiff = pticks->total - tmp.total;
340 udiff = pticks->used - tmp.used;
341
342 if (tdiff == 0) {
343 return 0.0;
344 } else if (tdiff < (udiff + kdiff)) {
345 tdiff = udiff + kdiff;
346 }
347 *pkernelLoad = (kdiff / (double)tdiff);
348 // BUG9044876, normalize return values to sane values
349 *pkernelLoad = MAX2<double>(*pkernelLoad, 0.0);
350 *pkernelLoad = MIN2<double>(*pkernelLoad, 1.0);
351
352 user_load = (udiff / (double)tdiff);
353 user_load = MAX2<double>(user_load, 0.0);
354 user_load = MIN2<double>(user_load, 1.0);
355
356 return user_load;
357 }
358
parse_stat(_SCANFMT_ const char * fmt,...)359 static int SCANF_ARGS(1, 2) parse_stat(_SCANFMT_ const char* fmt, ...) {
360 return OS_ERR;
361 }
362
get_noof_context_switches(uint64_t * switches)363 static int get_noof_context_switches(uint64_t* switches) {
364 return parse_stat("ctxt " UINT64_FORMAT "\n", switches);
365 }
366
367 /** returns boot time in _seconds_ since epoch */
get_boot_time(uint64_t * time)368 static int get_boot_time(uint64_t* time) {
369 return parse_stat("btime " UINT64_FORMAT "\n", time);
370 }
371
perf_context_switch_rate(double * rate)372 static int perf_context_switch_rate(double* rate) {
373 static pthread_mutex_t contextSwitchLock = PTHREAD_MUTEX_INITIALIZER;
374 static uint64_t bootTime;
375 static uint64_t lastTimeNanos;
376 static uint64_t lastSwitches;
377 static double lastRate;
378
379 uint64_t bt = 0;
380 int res = 0;
381
382 // First time through bootTime will be zero.
383 if (bootTime == 0) {
384 uint64_t tmp;
385 if (get_boot_time(&tmp) < 0) {
386 return OS_ERR;
387 }
388 bt = tmp * 1000;
389 }
390
391 res = OS_OK;
392
393 pthread_mutex_lock(&contextSwitchLock);
394 {
395
396 uint64_t sw;
397 s8 t, d;
398
399 if (bootTime == 0) {
400 // First interval is measured from boot time which is
401 // seconds since the epoch. Thereafter we measure the
402 // elapsed time using javaTimeNanos as it is monotonic-
403 // non-decreasing.
404 lastTimeNanos = os::javaTimeNanos();
405 t = os::javaTimeMillis();
406 d = t - bt;
407 // keep bootTime zero for now to use as a first-time-through flag
408 } else {
409 t = os::javaTimeNanos();
410 d = nanos_to_millis(t - lastTimeNanos);
411 }
412
413 if (d == 0) {
414 *rate = lastRate;
415 } else if (get_noof_context_switches(&sw) == 0) {
416 *rate = ( (double)(sw - lastSwitches) / d ) * 1000;
417 lastRate = *rate;
418 lastSwitches = sw;
419 if (bootTime != 0) {
420 lastTimeNanos = t;
421 }
422 } else {
423 *rate = 0;
424 res = OS_ERR;
425 }
426 if (*rate <= 0) {
427 *rate = 0;
428 lastRate = 0;
429 }
430
431 if (bootTime == 0) {
432 bootTime = bt;
433 }
434 }
435 pthread_mutex_unlock(&contextSwitchLock);
436
437 return res;
438 }
439
440 class CPUPerformanceInterface::CPUPerformance : public CHeapObj<mtInternal> {
441 friend class CPUPerformanceInterface;
442 private:
443 CPUPerfCounters _counters;
444
445 int cpu_load(int which_logical_cpu, double* cpu_load);
446 int context_switch_rate(double* rate);
447 int cpu_load_total_process(double* cpu_load);
448 int cpu_loads_process(double* pjvmUserLoad, double* pjvmKernelLoad, double* psystemTotalLoad);
449
450 public:
451 CPUPerformance();
452 bool initialize();
453 ~CPUPerformance();
454 };
455
CPUPerformance()456 CPUPerformanceInterface::CPUPerformance::CPUPerformance() {
457 _counters.nProcs = os::active_processor_count();
458 _counters.cpus = NULL;
459 }
460
initialize()461 bool CPUPerformanceInterface::CPUPerformance::initialize() {
462 size_t array_entry_count = _counters.nProcs + 1;
463 _counters.cpus = NEW_C_HEAP_ARRAY(CPUPerfTicks, array_entry_count, mtInternal);
464 memset(_counters.cpus, 0, array_entry_count * sizeof(*_counters.cpus));
465
466 // For the CPU load total
467 get_total_ticks(-1, &_counters.cpus[_counters.nProcs]);
468
469 // For each CPU
470 for (int i = 0; i < _counters.nProcs; i++) {
471 get_total_ticks(i, &_counters.cpus[i]);
472 }
473 // For JVM load
474 get_jvm_ticks(&_counters.jvmTicks);
475
476 // initialize context switch system
477 // the double is only for init
478 double init_ctx_switch_rate;
479 perf_context_switch_rate(&init_ctx_switch_rate);
480
481 return true;
482 }
483
~CPUPerformance()484 CPUPerformanceInterface::CPUPerformance::~CPUPerformance() {
485 if (_counters.cpus != NULL) {
486 FREE_C_HEAP_ARRAY(char, _counters.cpus);
487 }
488 }
489
cpu_load(int which_logical_cpu,double * cpu_load)490 int CPUPerformanceInterface::CPUPerformance::cpu_load(int which_logical_cpu, double* cpu_load) {
491 double u, s;
492 u = get_cpu_load(which_logical_cpu, &_counters, &s, CPU_LOAD_GLOBAL);
493 if (u < 0) {
494 *cpu_load = 0.0;
495 return OS_ERR;
496 }
497 // Cap total systemload to 1.0
498 *cpu_load = MIN2<double>((u + s), 1.0);
499 return OS_OK;
500 }
501
cpu_load_total_process(double * cpu_load)502 int CPUPerformanceInterface::CPUPerformance::cpu_load_total_process(double* cpu_load) {
503 double u, s;
504 u = get_cpu_load(-1, &_counters, &s, CPU_LOAD_VM_ONLY);
505 if (u < 0) {
506 *cpu_load = 0.0;
507 return OS_ERR;
508 }
509 *cpu_load = u + s;
510 return OS_OK;
511 }
512
cpu_loads_process(double * pjvmUserLoad,double * pjvmKernelLoad,double * psystemTotalLoad)513 int CPUPerformanceInterface::CPUPerformance::cpu_loads_process(double* pjvmUserLoad, double* pjvmKernelLoad, double* psystemTotalLoad) {
514 double u, s, t;
515
516 assert(pjvmUserLoad != NULL, "pjvmUserLoad not inited");
517 assert(pjvmKernelLoad != NULL, "pjvmKernelLoad not inited");
518 assert(psystemTotalLoad != NULL, "psystemTotalLoad not inited");
519
520 u = get_cpu_load(-1, &_counters, &s, CPU_LOAD_VM_ONLY);
521 if (u < 0) {
522 *pjvmUserLoad = 0.0;
523 *pjvmKernelLoad = 0.0;
524 *psystemTotalLoad = 0.0;
525 return OS_ERR;
526 }
527
528 cpu_load(-1, &t);
529 // clamp at user+system and 1.0
530 if (u + s > t) {
531 t = MIN2<double>(u + s, 1.0);
532 }
533
534 *pjvmUserLoad = u;
535 *pjvmKernelLoad = s;
536 *psystemTotalLoad = t;
537
538 return OS_OK;
539 }
540
context_switch_rate(double * rate)541 int CPUPerformanceInterface::CPUPerformance::context_switch_rate(double* rate) {
542 return perf_context_switch_rate(rate);
543 }
544
CPUPerformanceInterface()545 CPUPerformanceInterface::CPUPerformanceInterface() {
546 _impl = NULL;
547 }
548
initialize()549 bool CPUPerformanceInterface::initialize() {
550 _impl = new CPUPerformanceInterface::CPUPerformance();
551 return _impl->initialize();
552 }
553
~CPUPerformanceInterface()554 CPUPerformanceInterface::~CPUPerformanceInterface() {
555 if (_impl != NULL) {
556 delete _impl;
557 }
558 }
559
cpu_load(int which_logical_cpu,double * cpu_load) const560 int CPUPerformanceInterface::cpu_load(int which_logical_cpu, double* cpu_load) const {
561 return _impl->cpu_load(which_logical_cpu, cpu_load);
562 }
563
cpu_load_total_process(double * cpu_load) const564 int CPUPerformanceInterface::cpu_load_total_process(double* cpu_load) const {
565 return _impl->cpu_load_total_process(cpu_load);
566 }
567
cpu_loads_process(double * pjvmUserLoad,double * pjvmKernelLoad,double * psystemTotalLoad) const568 int CPUPerformanceInterface::cpu_loads_process(double* pjvmUserLoad, double* pjvmKernelLoad, double* psystemTotalLoad) const {
569 return _impl->cpu_loads_process(pjvmUserLoad, pjvmKernelLoad, psystemTotalLoad);
570 }
571
context_switch_rate(double * rate) const572 int CPUPerformanceInterface::context_switch_rate(double* rate) const {
573 return _impl->context_switch_rate(rate);
574 }
575
576 class SystemProcessInterface::SystemProcesses : public CHeapObj<mtInternal> {
577 friend class SystemProcessInterface;
578 private:
579 class ProcessIterator : public CHeapObj<mtInternal> {
580 friend class SystemProcessInterface::SystemProcesses;
581 private:
582 DIR* _dir;
583 struct dirent* _entry;
584 bool _valid;
585 char _exeName[PATH_MAX];
586 char _exePath[PATH_MAX];
587
588 ProcessIterator();
589 ~ProcessIterator();
590 bool initialize();
591
is_valid() const592 bool is_valid() const { return _valid; }
593 bool is_valid_entry(struct dirent* entry) const;
594 bool is_dir(const char* name) const;
595 int fsize(const char* name, uint64_t& size) const;
596
597 char* allocate_string(const char* str) const;
598 void get_exe_name();
599 char* get_exe_path();
600 char* get_cmdline();
601
602 int current(SystemProcess* process_info);
603 int next_process();
604 };
605
606 ProcessIterator* _iterator;
607 SystemProcesses();
608 bool initialize();
609 ~SystemProcesses();
610
611 //information about system processes
612 int system_processes(SystemProcess** system_processes, int* no_of_sys_processes) const;
613 };
614
is_dir(const char * name) const615 bool SystemProcessInterface::SystemProcesses::ProcessIterator::is_dir(const char* name) const {
616 struct stat mystat;
617 int ret_val = 0;
618
619 ret_val = stat(name, &mystat);
620 if (ret_val < 0) {
621 return false;
622 }
623 ret_val = S_ISDIR(mystat.st_mode);
624 return ret_val > 0;
625 }
626
fsize(const char * name,uint64_t & size) const627 int SystemProcessInterface::SystemProcesses::ProcessIterator::fsize(const char* name, uint64_t& size) const {
628 assert(name != NULL, "name pointer is NULL!");
629 size = 0;
630 struct stat fbuf;
631
632 if (stat(name, &fbuf) < 0) {
633 return OS_ERR;
634 }
635 size = fbuf.st_size;
636 return OS_OK;
637 }
638
639 // if it has a numeric name, is a directory and has a 'stat' file in it
is_valid_entry(struct dirent * entry) const640 bool SystemProcessInterface::SystemProcesses::ProcessIterator::is_valid_entry(struct dirent* entry) const {
641 char buffer[PATH_MAX];
642 uint64_t size = 0;
643
644 if (atoi(entry->d_name) != 0) {
645 jio_snprintf(buffer, PATH_MAX, "/proc/%s", entry->d_name);
646 buffer[PATH_MAX - 1] = '\0';
647
648 if (is_dir(buffer)) {
649 jio_snprintf(buffer, PATH_MAX, "/proc/%s/stat", entry->d_name);
650 buffer[PATH_MAX - 1] = '\0';
651 if (fsize(buffer, size) != OS_ERR) {
652 return true;
653 }
654 }
655 }
656 return false;
657 }
658
659 // get exe-name from /proc/<pid>/stat
get_exe_name()660 void SystemProcessInterface::SystemProcesses::ProcessIterator::get_exe_name() {
661 FILE* fp;
662 char buffer[PATH_MAX];
663
664 jio_snprintf(buffer, PATH_MAX, "/proc/%s/stat", _entry->d_name);
665 buffer[PATH_MAX - 1] = '\0';
666 if ((fp = fopen(buffer, "r")) != NULL) {
667 if (fgets(buffer, PATH_MAX, fp) != NULL) {
668 char* start, *end;
669 // exe-name is between the first pair of ( and )
670 start = strchr(buffer, '(');
671 if (start != NULL && start[1] != '\0') {
672 start++;
673 end = strrchr(start, ')');
674 if (end != NULL) {
675 size_t len;
676 len = MIN2<size_t>(end - start, sizeof(_exeName) - 1);
677 memcpy(_exeName, start, len);
678 _exeName[len] = '\0';
679 }
680 }
681 }
682 fclose(fp);
683 }
684 }
685
686 // get command line from /proc/<pid>/cmdline
get_cmdline()687 char* SystemProcessInterface::SystemProcesses::ProcessIterator::get_cmdline() {
688 FILE* fp;
689 char buffer[PATH_MAX];
690 char* cmdline = NULL;
691
692 jio_snprintf(buffer, PATH_MAX, "/proc/%s/cmdline", _entry->d_name);
693 buffer[PATH_MAX - 1] = '\0';
694 if ((fp = fopen(buffer, "r")) != NULL) {
695 size_t size = 0;
696 char dummy;
697
698 // find out how long the file is (stat always returns 0)
699 while (fread(&dummy, 1, 1, fp) == 1) {
700 size++;
701 }
702 if (size > 0) {
703 cmdline = NEW_C_HEAP_ARRAY(char, size + 1, mtInternal);
704 cmdline[0] = '\0';
705 if (fseek(fp, 0, SEEK_SET) == 0) {
706 if (fread(cmdline, 1, size, fp) == size) {
707 // the file has the arguments separated by '\0',
708 // so we translate '\0' to ' '
709 for (size_t i = 0; i < size; i++) {
710 if (cmdline[i] == '\0') {
711 cmdline[i] = ' ';
712 }
713 }
714 cmdline[size] = '\0';
715 }
716 }
717 }
718 fclose(fp);
719 }
720 return cmdline;
721 }
722
723 // get full path to exe from /proc/<pid>/exe symlink
get_exe_path()724 char* SystemProcessInterface::SystemProcesses::ProcessIterator::get_exe_path() {
725 char buffer[PATH_MAX];
726
727 jio_snprintf(buffer, PATH_MAX, "/proc/%s/exe", _entry->d_name);
728 buffer[PATH_MAX - 1] = '\0';
729 return realpath(buffer, _exePath);
730 }
731
allocate_string(const char * str) const732 char* SystemProcessInterface::SystemProcesses::ProcessIterator::allocate_string(const char* str) const {
733 if (str != NULL) {
734 return os::strdup_check_oom(str, mtInternal);
735 }
736 return NULL;
737 }
738
current(SystemProcess * process_info)739 int SystemProcessInterface::SystemProcesses::ProcessIterator::current(SystemProcess* process_info) {
740 if (!is_valid()) {
741 return OS_ERR;
742 }
743
744 process_info->set_pid(atoi(_entry->d_name));
745
746 get_exe_name();
747 process_info->set_name(allocate_string(_exeName));
748
749 if (get_exe_path() != NULL) {
750 process_info->set_path(allocate_string(_exePath));
751 }
752
753 char* cmdline = NULL;
754 cmdline = get_cmdline();
755 if (cmdline != NULL) {
756 process_info->set_command_line(allocate_string(cmdline));
757 FREE_C_HEAP_ARRAY(char, cmdline);
758 }
759
760 return OS_OK;
761 }
762
next_process()763 int SystemProcessInterface::SystemProcesses::ProcessIterator::next_process() {
764 if (!is_valid()) {
765 return OS_ERR;
766 }
767
768 do {
769 _entry = os::readdir(_dir);
770 if (_entry == NULL) {
771 // Error or reached end. Could use errno to distinguish those cases.
772 _valid = false;
773 return OS_ERR;
774 }
775 } while(!is_valid_entry(_entry));
776
777 _valid = true;
778 return OS_OK;
779 }
780
ProcessIterator()781 SystemProcessInterface::SystemProcesses::ProcessIterator::ProcessIterator() {
782 _dir = NULL;
783 _entry = NULL;
784 _valid = false;
785 }
786
initialize()787 bool SystemProcessInterface::SystemProcesses::ProcessIterator::initialize() {
788 // Not yet implemented.
789 return false;
790 }
791
~ProcessIterator()792 SystemProcessInterface::SystemProcesses::ProcessIterator::~ProcessIterator() {
793 if (_dir != NULL) {
794 os::closedir(_dir);
795 }
796 }
797
SystemProcesses()798 SystemProcessInterface::SystemProcesses::SystemProcesses() {
799 _iterator = NULL;
800 }
801
initialize()802 bool SystemProcessInterface::SystemProcesses::initialize() {
803 _iterator = new SystemProcessInterface::SystemProcesses::ProcessIterator();
804 return _iterator->initialize();
805 }
806
~SystemProcesses()807 SystemProcessInterface::SystemProcesses::~SystemProcesses() {
808 if (_iterator != NULL) {
809 delete _iterator;
810 }
811 }
812
system_processes(SystemProcess ** system_processes,int * no_of_sys_processes) const813 int SystemProcessInterface::SystemProcesses::system_processes(SystemProcess** system_processes, int* no_of_sys_processes) const {
814 assert(system_processes != NULL, "system_processes pointer is NULL!");
815 assert(no_of_sys_processes != NULL, "system_processes counter pointers is NULL!");
816 assert(_iterator != NULL, "iterator is NULL!");
817
818 // initialize pointers
819 *no_of_sys_processes = 0;
820 *system_processes = NULL;
821
822 while (_iterator->is_valid()) {
823 SystemProcess* tmp = new SystemProcess();
824 _iterator->current(tmp);
825
826 //if already existing head
827 if (*system_processes != NULL) {
828 //move "first to second"
829 tmp->set_next(*system_processes);
830 }
831 // new head
832 *system_processes = tmp;
833 // increment
834 (*no_of_sys_processes)++;
835 // step forward
836 _iterator->next_process();
837 }
838 return OS_OK;
839 }
840
system_processes(SystemProcess ** system_procs,int * no_of_sys_processes) const841 int SystemProcessInterface::system_processes(SystemProcess** system_procs, int* no_of_sys_processes) const {
842 return _impl->system_processes(system_procs, no_of_sys_processes);
843 }
844
SystemProcessInterface()845 SystemProcessInterface::SystemProcessInterface() {
846 _impl = NULL;
847 }
848
initialize()849 bool SystemProcessInterface::initialize() {
850 _impl = new SystemProcessInterface::SystemProcesses();
851 return _impl->initialize();
852 }
853
~SystemProcessInterface()854 SystemProcessInterface::~SystemProcessInterface() {
855 if (_impl != NULL) {
856 delete _impl;
857 }
858 }
859
CPUInformationInterface()860 CPUInformationInterface::CPUInformationInterface() {
861 _cpu_info = NULL;
862 }
863
initialize()864 bool CPUInformationInterface::initialize() {
865 _cpu_info = new CPUInformation();
866 _cpu_info->set_number_of_hardware_threads(VM_Version_Ext::number_of_threads());
867 _cpu_info->set_number_of_cores(VM_Version_Ext::number_of_cores());
868 _cpu_info->set_number_of_sockets(VM_Version_Ext::number_of_sockets());
869 _cpu_info->set_cpu_name(VM_Version_Ext::cpu_name());
870 _cpu_info->set_cpu_description(VM_Version_Ext::cpu_description());
871 return true;
872 }
873
~CPUInformationInterface()874 CPUInformationInterface::~CPUInformationInterface() {
875 if (_cpu_info != NULL) {
876 if (_cpu_info->cpu_name() != NULL) {
877 const char* cpu_name = _cpu_info->cpu_name();
878 FREE_C_HEAP_ARRAY(char, cpu_name);
879 _cpu_info->set_cpu_name(NULL);
880 }
881 if (_cpu_info->cpu_description() != NULL) {
882 const char* cpu_desc = _cpu_info->cpu_description();
883 FREE_C_HEAP_ARRAY(char, cpu_desc);
884 _cpu_info->set_cpu_description(NULL);
885 }
886 delete _cpu_info;
887 }
888 }
889
cpu_information(CPUInformation & cpu_info)890 int CPUInformationInterface::cpu_information(CPUInformation& cpu_info) {
891 if (_cpu_info == NULL) {
892 return OS_ERR;
893 }
894
895 cpu_info = *_cpu_info; // shallow copy assignment
896 return OS_OK;
897 }
898
899 class NetworkPerformanceInterface::NetworkPerformance : public CHeapObj<mtInternal> {
900 friend class NetworkPerformanceInterface;
901 private:
902 NetworkPerformance();
903 NONCOPYABLE(NetworkPerformance);
904 bool initialize();
905 ~NetworkPerformance();
906 int network_utilization(NetworkInterface** network_interfaces) const;
907 };
908
NetworkPerformance()909 NetworkPerformanceInterface::NetworkPerformance::NetworkPerformance() {
910
911 }
912
initialize()913 bool NetworkPerformanceInterface::NetworkPerformance::initialize() {
914 return true;
915 }
916
~NetworkPerformance()917 NetworkPerformanceInterface::NetworkPerformance::~NetworkPerformance() {
918 }
919
network_utilization(NetworkInterface ** network_interfaces) const920 int NetworkPerformanceInterface::NetworkPerformance::network_utilization(NetworkInterface** network_interfaces) const
921 {
922 return FUNCTIONALITY_NOT_IMPLEMENTED;
923 }
924
NetworkPerformanceInterface()925 NetworkPerformanceInterface::NetworkPerformanceInterface() {
926 _impl = NULL;
927 }
928
~NetworkPerformanceInterface()929 NetworkPerformanceInterface::~NetworkPerformanceInterface() {
930 if (_impl != NULL) {
931 delete _impl;
932 }
933 }
934
initialize()935 bool NetworkPerformanceInterface::initialize() {
936 _impl = new NetworkPerformanceInterface::NetworkPerformance();
937 return _impl->initialize();
938 }
939
network_utilization(NetworkInterface ** network_interfaces) const940 int NetworkPerformanceInterface::network_utilization(NetworkInterface** network_interfaces) const {
941 return _impl->network_utilization(network_interfaces);
942 }
943