1 /*
  2  * Copyright (c) 2001, 2025, 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 "classfile/vmSymbols.hpp"
 26 #include "jvm.h"
 27 #include "logging/log.hpp"
 28 #include "memory/allocation.inline.hpp"
 29 #include "oops/oop.inline.hpp"
 30 #include "runtime/handles.inline.hpp"
 31 #include "runtime/java.hpp"
 32 #include "runtime/mutex.hpp"
 33 #include "runtime/mutexLocker.hpp"
 34 #include "runtime/os.hpp"
 35 #include "runtime/perfData.inline.hpp"
 36 #include "utilities/exceptions.hpp"
 37 #include "utilities/globalCounter.inline.hpp"
 38 #include "utilities/globalDefinitions.hpp"
 39 
 40 PerfDataList*   PerfDataManager::_all = nullptr;
 41 PerfDataList*   PerfDataManager::_sampled = nullptr;
 42 PerfDataList*   PerfDataManager::_constants = nullptr;
 43 volatile bool   PerfDataManager::_has_PerfData = 0;
 44 
 45 /*
 46  * The jvmstat global and subsystem jvmstat counter name spaces. The top
 47  * level name spaces imply the interface stability level of the counter,
 48  * which generally follows the Java package, class, and property naming
 49  * conventions. The CounterNS enumeration values should be used to index
 50  * into this array.
 51  */
 52 const char* PerfDataManager::_name_spaces[] = {
 53   // top level name spaces
 54   "java",                   // stable and supported name space
 55   "com.sun",                // unstable but supported name space
 56   "sun",                    // unstable and unsupported name space
 57   // subsystem name spaces
 58   "java.gc",                // Garbage Collection name spaces
 59   "com.sun.gc",
 60   "sun.gc",
 61   "java.ci",                // Compiler name spaces
 62   "com.sun.ci",
 63   "sun.ci",
 64   "java.cls",               // Class Loader name spaces
 65   "com.sun.cls",
 66   "sun.cls",
 67   "java.rt",                // Runtime name spaces
 68   "com.sun.rt",
 69   "sun.rt",
 70   "java.os",                // Operating System name spaces
 71   "com.sun.os",
 72   "sun.os",
 73   "java.threads",           // Threads System name spaces
 74   "com.sun.threads",
 75   "sun.threads",
 76   "java.threads.cpu_time", //Thread CPU time name spaces
 77   "com.sun.threads.cpu_time",
 78   "sun.threads.cpu_time",
 79   "java.property",          // Java Property name spaces
 80   "com.sun.property",
 81   "sun.property",
 82   "",
 83 };
 84 
 85 PerfData::PerfData(CounterNS ns, const char* name, Units u, Variability v)
 86                   : _name(nullptr), _v(v), _u(u), _on_c_heap(false), _valuep(nullptr) {
 87 
 88   const char* prefix = PerfDataManager::ns_to_string(ns);
 89 
 90   const size_t _name_size = strlen(name) + strlen(prefix) + 2;
 91   _name = NEW_C_HEAP_ARRAY(char, _name_size, mtInternal);
 92   assert(strlen(name) != 0, "invalid name");
 93 
 94   if (ns == NULL_NS) {
 95      // No prefix is added to counters with the NULL_NS namespace.
 96      strcpy(_name, name);
 97      // set the F_Supported flag based on the counter name prefix.
 98      if (PerfDataManager::is_stable_supported(_name) ||
 99          PerfDataManager::is_unstable_supported(_name)) {
100        _flags = F_Supported;
101      }
102      else {
103        _flags = F_None;
104      }
105   }
106   else {
107     os::snprintf_checked(_name, _name_size, "%s.%s", prefix, name);
108     // set the F_Supported flag based on the given namespace.
109     if (PerfDataManager::is_stable_supported(ns) ||
110         PerfDataManager::is_unstable_supported(ns)) {
111       _flags = F_Supported;
112     }
113     else {
114       _flags = F_None;
115     }
116   }
117 }
118 
119 PerfData::~PerfData() {
120   FREE_C_HEAP_ARRAY(char, _name);
121   if (is_on_c_heap()) {
122     FREE_C_HEAP_ARRAY(PerfDataEntry, _pdep);
123   }
124 }
125 
126 void PerfData::create_entry(BasicType dtype, size_t dsize, size_t vlen) {
127 
128   size_t dlen = vlen==0 ? 1 : vlen;
129 
130   size_t namelen = strlen(name()) + 1;  // include null terminator
131   size_t size = sizeof(PerfDataEntry) + namelen;
132   size_t pad_length = ((size % dsize) == 0) ? 0 : dsize - (size % dsize);
133   size += pad_length;
134   size_t data_start = size;
135   size += (dsize * dlen);
136 
137   // align size to assure allocation in units of 8 bytes
138   int align = sizeof(jlong) - 1;
139   size = ((size + align) & ~align);
140   char* psmp = PerfMemory::alloc(size);
141 
142   if (psmp == nullptr) {
143     // out of PerfMemory memory resources. allocate on the C heap
144     // to avoid vm termination.
145     psmp = NEW_C_HEAP_ARRAY(char, size, mtInternal);
146     _on_c_heap = true;
147   }
148 
149   // compute the addresses for the name and data
150   char* cname = psmp + sizeof(PerfDataEntry);
151 
152   // data is in the last dsize*dlen bytes of the entry
153   void* valuep = (void*) (psmp + data_start);
154 
155   assert(is_on_c_heap() || PerfMemory::contains(cname), "just checking");
156   assert(is_on_c_heap() || PerfMemory::contains((char*)valuep), "just checking");
157 
158   // copy the name, including null terminator, into PerfData memory
159   strcpy(cname, name());
160 
161 
162   // set the header values in PerfData memory
163   PerfDataEntry* pdep = (PerfDataEntry*)psmp;
164   pdep->entry_length = (jint)size;
165   pdep->name_offset = (jint) ((uintptr_t) cname - (uintptr_t) psmp);
166   pdep->vector_length = (jint)vlen;
167   pdep->data_type = (jbyte) type2char(dtype);
168   pdep->data_units = units();
169   pdep->data_variability = variability();
170   pdep->flags = (jbyte)flags();
171   pdep->data_offset = (jint) data_start;
172 
173   log_debug(perf, datacreation)("name = %s, dtype = %d, variability = %d,"
174                                 " units = %d, dsize = %zu, vlen = %zu,"
175                                 " pad_length = %zu, size = %zu, on_c_heap = %s,"
176                                 " address = " INTPTR_FORMAT ","
177                                 " data address = " INTPTR_FORMAT,
178                                 cname, dtype, variability(),
179                                 units(), dsize, vlen,
180                                 pad_length, size, is_on_c_heap() ? "TRUE":"FALSE",
181                                 p2i(psmp), p2i(valuep));
182 
183   // record the start of the entry and the location of the data field.
184   _pdep = pdep;
185   _valuep = valuep;
186 
187   // mark the PerfData memory region as having been updated.
188   PerfMemory::mark_updated();
189 }
190 
191 bool PerfData::name_equals(const char* name) const {
192   return strcmp(name, this->name()) == 0;
193 }
194 
195 PerfLong::PerfLong(CounterNS ns, const char* namep, Units u, Variability v)
196                  : PerfData(ns, namep, u, v) {
197 
198   create_entry(T_LONG, sizeof(jlong));
199 }
200 
201 PerfLongVariant::PerfLongVariant(CounterNS ns, const char* namep, Units u,
202                                  Variability v, PerfLongSampleHelper* helper)
203                                 : PerfLong(ns, namep, u, v),
204                                   _sample_helper(helper) {
205 
206   sample();
207 }
208 
209 void PerfLongVariant::sample() {
210   if (_sample_helper != nullptr) {
211     *(jlong*)_valuep = _sample_helper->take_sample();
212   }
213 }
214 
215 PerfByteArray::PerfByteArray(CounterNS ns, const char* namep, Units u,
216                              Variability v, jint length)
217                             : PerfData(ns, namep, u, v), _length(length) {
218 
219   create_entry(T_BYTE, sizeof(jbyte), (size_t)_length);
220 }
221 
222 void PerfString::set_string(const char* s2) {
223 
224   // copy n bytes of the string, assuring the null string is
225   // copied if s2 == nullptr.
226   strncpy((char *)_valuep, s2 == nullptr ? "" : s2, _length);
227 
228   // assure the string is null terminated when strlen(s2) >= _length
229   ((char*)_valuep)[_length-1] = '\0';
230 }
231 
232 PerfStringConstant::PerfStringConstant(CounterNS ns, const char* namep,
233                                        const char* initial_value)
234                      : PerfString(ns, namep, V_Constant,
235                                   initial_value == nullptr ? 1 :
236                                   MIN2((jint)(strlen((char*)initial_value)+1),
237                                        (jint)(PerfMaxStringConstLength+1)),
238                                   initial_value) {
239 
240   if (PrintMiscellaneous && Verbose) {
241     if (is_valid() && initial_value != nullptr &&
242         ((jint)strlen(initial_value) > (jint)PerfMaxStringConstLength)) {
243 
244       warning("Truncating PerfStringConstant: name = %s,"
245               " length = " INT32_FORMAT ","
246               " PerfMaxStringConstLength = " INT32_FORMAT "\n",
247               namep,
248               (jint)strlen(initial_value),
249               (jint)PerfMaxStringConstLength);
250     }
251   }
252 }
253 
254 
255 void PerfDataManager::destroy() {
256 
257   if (_all == nullptr)
258     // destroy already called, or initialization never happened
259     return;
260 
261   // About to delete the counters than might still be accessed by other threads.
262   // The shutdown is performed in two stages: a) clear the flag to notify future
263   // counter users that we are at shutdown; b) sync up with current users, waiting
264   // for them to finish with counters.
265   //
266   Atomic::store(&_has_PerfData, false);
267   GlobalCounter::write_synchronize();
268 
269   log_debug(perf, datacreation)("Total = %d, Sampled = %d, Constants = %d",
270                                 _all->length(), _sampled == nullptr ? 0 : _sampled->length(),
271                                 _constants == nullptr ? 0 : _constants->length());
272 
273   for (int index = 0; index < _all->length(); index++) {
274     PerfData* p = _all->at(index);
275     delete p;
276   }
277 
278   delete(_all);
279   delete(_sampled);
280   delete(_constants);
281 
282   _all = nullptr;
283   _sampled = nullptr;
284   _constants = nullptr;
285 }
286 
287 void PerfDataManager::add_item(PerfData* p, bool sampled) {
288 
289   MutexLocker ml(PerfDataManager_lock);
290 
291   // Default sizes determined using -Xlog:perf+datacreation=debug
292   if (_all == nullptr) {
293     _all = new PerfDataList(191);
294     Atomic::release_store(&_has_PerfData, true);
295   }
296 
297   assert(!_all->contains(p->name()), "duplicate name added: %s", p->name());
298 
299   // add to the list of all perf data items
300   _all->append(p);
301 
302   if (p->variability() == PerfData::V_Constant) {
303     if (_constants == nullptr) {
304       _constants = new PerfDataList(51);
305     }
306     _constants->append(p);
307     return;
308   }
309 
310   if (sampled) {
311     if (_sampled == nullptr) {
312       _sampled = new PerfDataList(1);
313     }
314     _sampled->append(p);
315   }
316 }
317 
318 PerfDataList* PerfDataManager::sampled() {
319 
320   MutexLocker ml(PerfDataManager_lock);
321 
322   if (_sampled == nullptr)
323     return nullptr;
324 
325   PerfDataList* clone = _sampled->clone();
326   return clone;
327 }
328 
329 char* PerfDataManager::counter_name(const char* ns, const char* name) {
330    assert(ns != nullptr, "ns string required");
331    assert(name != nullptr, "name string required");
332 
333    size_t len = strlen(ns) + strlen(name) + 2;
334    char* result = NEW_RESOURCE_ARRAY(char, len);
335    os::snprintf_checked(result, len, "%s.%s", ns, name);
336    return result;
337 }
338 
339 char* PerfDataManager::name_space(const char* ns, const char* sub,
340                                   int instance) {
341    char intbuf[40];
342    jio_snprintf(intbuf, 40, UINT32_FORMAT, instance);
343    return name_space(ns, name_space(sub, intbuf));
344 }
345 
346 char *PerfDataManager::name_space(const char* ns, int instance) {
347    char intbuf[40];
348    jio_snprintf(intbuf, 40, UINT32_FORMAT, instance);
349    return name_space(ns, intbuf);
350 }
351 
352 PerfStringConstant* PerfDataManager::create_string_constant(CounterNS ns,
353                                                             const char* name,
354                                                             const char* s,
355                                                             TRAPS) {
356 
357   PerfStringConstant* p = new PerfStringConstant(ns, name, s);
358 
359   if (!p->is_valid()) {
360     // allocation of native resources failed.
361     delete p;
362     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
363   }
364 
365   add_item(p, false);
366 
367   return p;
368 }
369 
370 PerfLongConstant* PerfDataManager::create_long_constant(CounterNS ns,
371                                                         const char* name,
372                                                         PerfData::Units u,
373                                                         jlong val, TRAPS) {
374 
375   PerfLongConstant* p = new PerfLongConstant(ns, name, u, val);
376 
377   if (!p->is_valid()) {
378     // allocation of native resources failed.
379     delete p;
380     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
381   }
382 
383   add_item(p, false);
384 
385   return p;
386 }
387 
388 PerfStringVariable* PerfDataManager::create_string_variable(CounterNS ns,
389                                                             const char* name,
390                                                             int max_length,
391                                                             const char* s,
392                                                             TRAPS) {
393 
394   if (max_length == 0 && s != nullptr) max_length = (int)strlen(s);
395 
396   assert(max_length != 0, "PerfStringVariable with length 0");
397 
398   PerfStringVariable* p = new PerfStringVariable(ns, name, max_length, s);
399 
400   if (!p->is_valid()) {
401     // allocation of native resources failed.
402     delete p;
403     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
404   }
405 
406   add_item(p, false);
407 
408   return p;
409 }
410 
411 PerfLongVariable* PerfDataManager::create_long_variable(CounterNS ns,
412                                                         const char* name,
413                                                         PerfData::Units u,
414                                                         jlong ival, TRAPS) {
415 
416   PerfLongVariable* p = new PerfLongVariable(ns, name, u, ival);
417 
418   if (!p->is_valid()) {
419     // allocation of native resources failed.
420     delete p;
421     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
422   }
423 
424   add_item(p, false);
425 
426   return p;
427 }
428 
429 PerfLongVariable* PerfDataManager::create_long_variable(CounterNS ns,
430                                                         const char* name,
431                                                         PerfData::Units u,
432                                                         PerfSampleHelper* sh,
433                                                         TRAPS) {
434 
435   // Sampled counters not supported if UsePerfData is false
436   if (!UsePerfData) return nullptr;
437 
438   PerfLongVariable* p = new PerfLongVariable(ns, name, u, sh);
439 
440   if (!p->is_valid()) {
441     // allocation of native resources failed.
442     delete p;
443     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
444   }
445 
446   add_item(p, true);
447 
448   return p;
449 }
450 
451 PerfLongCounter* PerfDataManager::create_long_counter(CounterNS ns,
452                                                       const char* name,
453                                                       PerfData::Units u,
454                                                       jlong ival, TRAPS) {
455 
456   PerfLongCounter* p = new PerfLongCounter(ns, name, u, ival);
457 
458   if (!p->is_valid()) {
459     // allocation of native resources failed.
460     delete p;
461     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
462   }
463 
464   add_item(p, false);
465 
466   return p;
467 }
468 
469 PerfLongCounter* PerfDataManager::create_long_counter(CounterNS ns,
470                                                       const char* name,
471                                                       PerfData::Units u,
472                                                       PerfSampleHelper* sh,
473                                                       TRAPS) {
474 
475   // Sampled counters not supported if UsePerfData is false
476   if (!UsePerfData) return nullptr;
477 
478   PerfLongCounter* p = new PerfLongCounter(ns, name, u, sh);
479 
480   if (!p->is_valid()) {
481     // allocation of native resources failed.
482     delete p;
483     THROW_NULL(vmSymbols::java_lang_OutOfMemoryError());
484   }
485 
486   add_item(p, true);
487 
488   return p;
489 }
490 
491 PerfDataList::PerfDataList(int length) {
492 
493   _set = new (mtInternal) PerfDataArray(length, mtInternal);
494 }
495 
496 PerfDataList::PerfDataList(PerfDataList* p) {
497 
498   _set = new (mtInternal) PerfDataArray(p->length(), mtInternal);
499 
500   _set->appendAll(p->get_impl());
501 }
502 
503 PerfDataList::~PerfDataList() {
504 
505   delete _set;
506 
507 }
508 
509 PerfData* PerfDataList::find_by_name(const char* name) {
510 
511   int i = _set->find_if([&](PerfData* pd) { return pd->name_equals(name); });
512 
513   if (i >= 0 && i <= _set->length())
514     return _set->at(i);
515   else
516     return nullptr;
517 }
518 
519 PerfDataList* PerfDataList::clone() {
520 
521   PerfDataList* copy = new PerfDataList(this);
522 
523   assert(copy != nullptr, "just checking");
524 
525   return copy;
526 }
527 
528 PerfTraceTimeBase::~PerfTraceTimeBase() {
529   if (!UsePerfData || !_t->is_active()) return;
530   if (_counter != nullptr) {
531     _t->stop();
532     _counter->inc(_t->ticks());
533   }
534 }