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