1 /*
  2  * Copyright (c) 1998, 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 "code/debugInfoRec.hpp"
 26 #include "code/scopeDesc.hpp"
 27 #include "compiler/oopMap.hpp"
 28 #include "prims/jvmtiExport.hpp"
 29 #include "runtime/globals_extension.hpp"
 30 
 31 // Private definition.
 32 // There is one DIR_Chunk for each scope and values array.
 33 // A chunk can potentially be used more than once.
 34 // We keep track of these chunks in order to detect
 35 // repetition and enable sharing.
 36 class DIR_Chunk {
 37 private:
 38   int  _offset; // location in the stream of this scope
 39   int  _length; // number of bytes in the stream
 40   int  _hash;   // hash of stream bytes (for quicker reuse)
 41   DebugInformationRecorder* _DIR;
 42 
 43 public:
 44   int offset() { return _offset; }
 45 
 46   void* operator new(size_t ignore, DebugInformationRecorder* dir) throw() {
 47     assert(ignore == sizeof(DIR_Chunk), "");
 48     if (dir->_next_chunk >= dir->_next_chunk_limit) {
 49       const int CHUNK = 100;
 50       dir->_next_chunk = NEW_RESOURCE_ARRAY(DIR_Chunk, CHUNK);
 51       dir->_next_chunk_limit = dir->_next_chunk + CHUNK;
 52     }
 53     return dir->_next_chunk++;
 54   }
 55 
 56   DIR_Chunk(int offset, int length, DebugInformationRecorder* dir) {
 57     _offset = offset;
 58     _length = length;
 59     _DIR = dir;
 60     unsigned int hash = 0;
 61     address p = dir->stream()->buffer() + _offset;
 62     for (int i = 0; i < length; i++) {
 63       if (i == 6)  break;
 64       hash *= 127;
 65       hash += p[i];
 66     }
 67     _hash = hash;
 68   }
 69 
 70   DIR_Chunk* find_match(GrowableArray<DIR_Chunk*>* arr,
 71                         int start_index,
 72                         DebugInformationRecorder* dir) {
 73     int end_index = arr->length();
 74     int hash = this->_hash, length = this->_length;
 75     address buf = dir->stream()->buffer();
 76     for (int i = end_index; --i >= start_index; ) {
 77       DIR_Chunk* that = arr->at(i);
 78       if (hash   == that->_hash &&
 79           length == that->_length &&
 80           0 == memcmp(buf + this->_offset, buf + that->_offset, length)) {
 81         return that;
 82       }
 83     }
 84     return nullptr;
 85   }
 86 
 87   static int compare(DIR_Chunk* const & a, DIR_Chunk* const & b) {
 88     if (b->_hash > a->_hash) {
 89       return 1;
 90     }
 91     if (b->_hash < a->_hash) {
 92       return -1;
 93     }
 94     if (b->_length > a->_length) {
 95       return 1;
 96     }
 97     if (b->_length < a->_length) {
 98       return -1;
 99     }
100     address buf = a->_DIR->stream()->buffer();
101     return memcmp(buf + b->_offset, buf + a->_offset, a->_length);
102   }
103 };
104 
105 static inline bool compute_recording_non_safepoints() {
106   if (JvmtiExport::should_post_compiled_method_load()
107       && FLAG_IS_DEFAULT(DebugNonSafepoints)) {
108     // The default value of this flag is taken to be true,
109     // if JVMTI is looking at nmethod codes.
110     // We anticipate that JVMTI may wish to participate in profiling.
111     return true;
112   }
113 
114   // If the flag is set manually, use it, whether true or false.
115   // Otherwise, if JVMTI is not in the picture, use the default setting.
116   // (This is true in debug, just for the exercise, false in product mode.)
117   return DebugNonSafepoints;
118 }
119 
120 DebugInformationRecorder::DebugInformationRecorder(OopRecorder* oop_recorder)
121   : _recording_non_safepoints(compute_recording_non_safepoints())
122 {
123   _pcs_size   = 100;
124   _pcs        = NEW_RESOURCE_ARRAY(PcDesc, _pcs_size);
125   _pcs_length = 0;
126 
127   _prev_safepoint_pc = PcDesc::lower_offset_limit;
128 
129   _stream = new DebugInfoWriteStream(this, 10 * K);
130   // make sure that there is no stream_decode_offset that is zero
131   _stream->write_byte((jbyte)0xFF);
132 
133   // make sure that we can distinguish the value "serialized_null" from offsets
134   assert(_stream->position() > serialized_null, "sanity");
135 
136   _oop_recorder = oop_recorder;
137 
138   _all_chunks    = new GrowableArray<DIR_Chunk*>(300);
139   _next_chunk = _next_chunk_limit = nullptr;
140 
141   add_new_pc_offset(PcDesc::lower_offset_limit);  // sentinel record
142 
143   debug_only(_recording_state = rs_null);
144 }
145 
146 DebugInformationRecorder::DebugInformationRecorder(OopRecorder* oop_recorder, int data_size, int pcs_length)
147   : _recording_non_safepoints(compute_recording_non_safepoints())
148 {
149   _pcs_size   = _pcs_length = pcs_length;
150   _pcs        = NEW_RESOURCE_ARRAY(PcDesc, _pcs_size);
151 
152   _prev_safepoint_pc = PcDesc::lower_offset_limit;
153 
154   _stream = new DebugInfoWriteStream(this, data_size);
155   // make sure that there is no stream_decode_offset that is zero
156   _stream->write_byte((jbyte)0xFF);
157 
158   // make sure that we can distinguish the value "serialized_null" from offsets
159   assert(_stream->position() > serialized_null, "sanity");
160 
161   _oop_recorder = oop_recorder;
162 
163   _all_chunks = nullptr;
164   _next_chunk = _next_chunk_limit = nullptr;
165 
166   debug_only(_recording_state = rs_null);
167 }
168 
169 void DebugInformationRecorder::add_oopmap(int pc_offset, OopMap* map) {
170   // !!!!! Preserve old style handling of oopmaps for now
171   _oopmaps->add_gc_map(pc_offset, map);
172 }
173 
174 void DebugInformationRecorder::add_safepoint(int pc_offset, OopMap* map) {
175   assert(!_oop_recorder->is_complete(), "not frozen yet");
176   // Store the new safepoint
177 
178   // Add the oop map
179   add_oopmap(pc_offset, map);
180 
181   add_new_pc_offset(pc_offset);
182 
183   assert(_recording_state == rs_null, "nesting of recording calls");
184   debug_only(_recording_state = rs_safepoint);
185 }
186 
187 void DebugInformationRecorder::add_non_safepoint(int pc_offset) {
188   assert(!_oop_recorder->is_complete(), "not frozen yet");
189   assert(_recording_non_safepoints, "must be recording non-safepoints");
190 
191   add_new_pc_offset(pc_offset);
192 
193   assert(_recording_state == rs_null, "nesting of recording calls");
194   debug_only(_recording_state = rs_non_safepoint);
195 }
196 
197 void DebugInformationRecorder::add_new_pc_offset(int pc_offset) {
198   assert(_pcs_length == 0 || last_pc()->pc_offset() < pc_offset,
199          "must specify a new, larger pc offset: %d >= %d", last_pc()->pc_offset(), pc_offset);
200 
201   // add the pcdesc
202   if (_pcs_length == _pcs_size) {
203     // Expand
204     int     new_pcs_size = _pcs_size * 2;
205     PcDesc* new_pcs      = NEW_RESOURCE_ARRAY(PcDesc, new_pcs_size);
206     for (int index = 0; index < _pcs_length; index++) {
207       new_pcs[index] = _pcs[index];
208     }
209     _pcs_size = new_pcs_size;
210     _pcs      = new_pcs;
211   }
212   assert(_pcs_size > _pcs_length, "There must be room for after expanding");
213 
214   _pcs[_pcs_length++] = PcDesc(pc_offset, DebugInformationRecorder::serialized_null,
215                                DebugInformationRecorder::serialized_null);
216 }
217 
218 
219 int DebugInformationRecorder::serialize_monitor_values(GrowableArray<MonitorValue*>* monitors) {
220   if (monitors == nullptr || monitors->is_empty()) return DebugInformationRecorder::serialized_null;
221   assert(_recording_state == rs_safepoint, "must be recording a safepoint");
222   int result = stream()->position();
223   stream()->write_int(monitors->length());
224   for (int index = 0; index < monitors->length(); index++) {
225     monitors->at(index)->write_on(stream());
226   }
227   assert(result != serialized_null, "sanity");
228 
229   // (See comment below on DebugInformationRecorder::describe_scope.)
230   int shared_result = find_sharable_decode_offset(result);
231   if (shared_result != serialized_null) {
232     stream()->set_position(result);
233     result = shared_result;
234   }
235 
236   return result;
237 }
238 
239 
240 int DebugInformationRecorder::serialize_scope_values(GrowableArray<ScopeValue*>* values) {
241   if (values == nullptr || values->is_empty()) return DebugInformationRecorder::serialized_null;
242   assert(_recording_state == rs_safepoint, "must be recording a safepoint");
243   int result = stream()->position();
244   assert(result != serialized_null, "sanity");
245   stream()->write_int(values->length());
246   for (int index = 0; index < values->length(); index++) {
247     values->at(index)->write_on(stream());
248   }
249 
250   // (See comment below on DebugInformationRecorder::describe_scope.)
251   int shared_result = find_sharable_decode_offset(result);
252   if (shared_result != serialized_null) {
253     stream()->set_position(result);
254     result = shared_result;
255   }
256 
257   return result;
258 }
259 
260 
261 #ifndef PRODUCT
262 // These variables are put into one block to reduce relocations
263 // and make it simpler to print from the debugger.
264 static
265 struct dir_stats_struct {
266   int chunks_queried;
267   int chunks_shared;
268   int chunks_elided;
269 
270   void print() {
271     tty->print_cr("Debug Data Chunks: %d, shared %d, non-SP's elided %d",
272                   chunks_queried, chunks_shared, chunks_elided);
273   }
274 } dir_stats;
275 #endif //PRODUCT
276 
277 
278 int DebugInformationRecorder::find_sharable_decode_offset(int stream_offset) {
279   NOT_PRODUCT(++dir_stats.chunks_queried);
280   int stream_length = stream()->position() - stream_offset;
281   assert(stream_offset != serialized_null, "should not be null");
282   assert(stream_length != 0, "should not be empty");
283 
284   DIR_Chunk* ns = new(this) DIR_Chunk(stream_offset, stream_length, this);
285 
286   DIR_Chunk* match = _all_chunks->insert_sorted<DIR_Chunk::compare>(ns);
287   if (match != ns) {
288     // Found an existing chunk
289     NOT_PRODUCT(++dir_stats.chunks_shared);
290     assert(ns+1 == _next_chunk, "");
291     _next_chunk = ns;
292     return match->offset();
293   } else {
294     // Inserted this chunk, so nothing to do
295     return serialized_null;
296   }
297 }
298 
299 
300 // must call add_safepoint before: it sets PcDesc and this routine uses
301 // the last PcDesc set
302 void DebugInformationRecorder::describe_scope(int         pc_offset,
303                                               const methodHandle& methodH,
304                                               ciMethod*   method,
305                                               int         bci,
306                                               bool        reexecute,
307                                               bool        rethrow_exception,
308                                               bool        is_method_handle_invoke,
309                                               bool        return_oop,
310                                               bool        has_ea_local_in_scope,
311                                               bool        arg_escape,
312                                               DebugToken* locals,
313                                               DebugToken* expressions,
314                                               DebugToken* monitors) {
315   assert(_recording_state != rs_null, "nesting of recording calls");
316   PcDesc* last_pd = last_pc();
317   assert(last_pd->pc_offset() == pc_offset, "must be last pc");
318   int sender_stream_offset = last_pd->scope_decode_offset();
319   // update the stream offset of current pc desc
320   int stream_offset = stream()->position();
321   last_pd->set_scope_decode_offset(stream_offset);
322 
323   // Record flags into pcDesc.
324   last_pd->set_should_reexecute(reexecute);
325   last_pd->set_rethrow_exception(rethrow_exception);
326   last_pd->set_is_method_handle_invoke(is_method_handle_invoke);
327   last_pd->set_return_oop(return_oop);
328   last_pd->set_has_ea_local_in_scope(has_ea_local_in_scope);
329   last_pd->set_arg_escape(arg_escape);
330 
331   // serialize sender stream offset
332   stream()->write_int(sender_stream_offset);
333 
334   // serialize scope
335   Metadata* method_enc;
336   if (method != nullptr) {
337     method_enc = method->constant_encoding();
338   } else if (methodH.not_null()) {
339     method_enc = methodH();
340   } else {
341     method_enc = nullptr;
342   }
343   int method_enc_index = oop_recorder()->find_index(method_enc);
344   stream()->write_int(method_enc_index);
345   stream()->write_bci(bci);
346   assert(method == nullptr ||
347          (method->is_native() && bci == 0) ||
348          (!method->is_native() && 0 <= bci && bci < method->code_size()) ||
349          bci == -1, "illegal bci");
350 
351   // serialize the locals/expressions/monitors
352   stream()->write_int((intptr_t) locals);
353   stream()->write_int((intptr_t) expressions);
354   stream()->write_int((intptr_t) monitors);
355 
356   // Here's a tricky bit.  We just wrote some bytes.
357   // Wouldn't it be nice to find that we had already
358   // written those same bytes somewhere else?
359   // If we get lucky this way, reset the stream
360   // and reuse the old bytes.  By the way, this
361   // trick not only shares parent scopes, but also
362   // compresses equivalent non-safepoint PcDescs.
363   int shared_stream_offset = find_sharable_decode_offset(stream_offset);
364   if (shared_stream_offset != serialized_null) {
365     stream()->set_position(stream_offset);
366     last_pd->set_scope_decode_offset(shared_stream_offset);
367   }
368 }
369 
370 void DebugInformationRecorder::dump_object_pool(GrowableArray<ScopeValue*>* objects) {
371   guarantee( _pcs_length > 0, "safepoint must exist before describing scopes");
372   PcDesc* last_pd = &_pcs[_pcs_length-1];
373   if (objects != nullptr) {
374     for (int i = objects->length() - 1; i >= 0; i--) {
375       objects->at(i)->as_ObjectValue()->set_visited(false);
376     }
377   }
378   int offset = serialize_scope_values(objects);
379   last_pd->set_obj_decode_offset(offset);
380 }
381 
382 void DebugInformationRecorder::end_scopes(int pc_offset, bool is_safepoint) {
383   assert(_recording_state == (is_safepoint? rs_safepoint: rs_non_safepoint),
384          "nesting of recording calls");
385   debug_only(_recording_state = rs_null);
386 
387   // Try to compress away an equivalent non-safepoint predecessor.
388   // (This only works because we have previously recognized redundant
389   // scope trees and made them use a common scope_decode_offset.)
390   if (_pcs_length >= 2 && recording_non_safepoints()) {
391     PcDesc* last = last_pc();
392     PcDesc* prev = prev_pc();
393     // If prev is (a) not a safepoint and (b) has the same
394     // stream pointer, then it can be coalesced into the last.
395     // This is valid because non-safepoints are only sought
396     // with pc_desc_near, which (when it misses prev) will
397     // search forward until it finds last.
398     // In addition, it does not matter if the last PcDesc
399     // is for a safepoint or not.
400     if (_prev_safepoint_pc < prev->pc_offset() && prev->is_same_info(last)) {
401       assert(prev == last-1, "sane");
402       prev->set_pc_offset(pc_offset);
403       _pcs_length -= 1;
404       NOT_PRODUCT(++dir_stats.chunks_elided);
405     }
406   }
407 
408   // We have just recorded this safepoint.
409   // Remember it in case the previous paragraph needs to know.
410   if (is_safepoint) {
411     _prev_safepoint_pc = pc_offset;
412   }
413 }
414 
415 #ifdef ASSERT
416 bool DebugInformationRecorder::recorders_frozen() {
417   return _oop_recorder->is_complete();
418 }
419 
420 void DebugInformationRecorder::mark_recorders_frozen() {
421   _oop_recorder->freeze();
422 }
423 #endif // PRODUCT
424 
425 DebugToken* DebugInformationRecorder::create_scope_values(GrowableArray<ScopeValue*>* values) {
426   assert(!recorders_frozen(), "not frozen yet");
427   return (DebugToken*) (intptr_t) serialize_scope_values(values);
428 }
429 
430 
431 DebugToken* DebugInformationRecorder::create_monitor_values(GrowableArray<MonitorValue*>* monitors) {
432   assert(!recorders_frozen(), "not frozen yet");
433   return (DebugToken*) (intptr_t) serialize_monitor_values(monitors);
434 }
435 
436 
437 int DebugInformationRecorder::data_size() {
438   debug_only(mark_recorders_frozen());  // mark it "frozen" for asserts
439   return _stream->position();
440 }
441 
442 
443 int DebugInformationRecorder::pcs_size() {
444   debug_only(mark_recorders_frozen());  // mark it "frozen" for asserts
445   if (last_pc()->pc_offset() != PcDesc::upper_offset_limit)
446     add_new_pc_offset(PcDesc::upper_offset_limit);
447   return _pcs_length * sizeof(PcDesc);
448 }
449 
450 
451 void DebugInformationRecorder::copy_to(nmethod* nm) {
452   nm->copy_scopes_data(stream()->buffer(), stream()->position());
453   nm->copy_scopes_pcs(_pcs, _pcs_length);
454 }
455 
456 
457 void DebugInformationRecorder::verify(const nmethod* code) {
458   Unimplemented();
459 }
460 
461 #ifndef PRODUCT
462 void DebugInformationRecorder::print_statistics() {
463   dir_stats.print();
464 }
465 #endif //PRODUCT