< prev index next >

src/hotspot/share/jfr/recorder/repository/jfrEmergencyDump.cpp

Print this page


   1 /*
   2  * Copyright (c) 2012, 2019, 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 "jfr/jfrEvents.hpp"
  27 #include "jfr/jni/jfrJavaSupport.hpp"
  28 #include "jfr/leakprofiler/leakProfiler.hpp"
  29 #include "jfr/recorder/repository/jfrEmergencyDump.hpp"
  30 #include "jfr/recorder/service/jfrPostBox.hpp"
  31 #include "jfr/recorder/service/jfrRecorderService.hpp"
  32 #include "jfr/utilities/jfrTypes.hpp"
  33 #include "logging/log.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "runtime/atomic.hpp"
  36 #include "runtime/handles.inline.hpp"
  37 #include "runtime/globals.hpp"
  38 #include "runtime/mutexLocker.hpp"
  39 #include "runtime/os.hpp"
  40 #include "runtime/thread.inline.hpp"
  41 #include "utilities/growableArray.hpp"

  42 
  43 static const char vm_error_filename_fmt[] = "hs_err_pid%p.jfr";
  44 static const char vm_oom_filename_fmt[] = "hs_oom_pid%p.jfr";
  45 static const char vm_soe_filename_fmt[] = "hs_soe_pid%p.jfr";
  46 static const char chunk_file_jfr_ext[] = ".jfr";
  47 static const size_t iso8601_len = 19; // "YYYY-MM-DDTHH:MM:SS"































  48 
  49 static fio_fd open_exclusivly(const char* path) {

  50   return os::open(path, O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
  51 }
  52 














































































  53 static int file_sort(const char** const file1, const char** file2) {
  54   assert(NULL != *file1 && NULL != *file2, "invariant");
  55   int cmp = strncmp(*file1, *file2, iso8601_len);
  56   if (0 == cmp) {
  57     const char* const dot1 = strchr(*file1, '.');
  58     assert(NULL != dot1, "invariant");
  59     const char* const dot2 = strchr(*file2, '.');
  60     assert(NULL != dot2, "invariant");
  61     ptrdiff_t file1_len = dot1 - *file1;
  62     ptrdiff_t file2_len = dot2 - *file2;
  63     if (file1_len < file2_len) {
  64       return -1;
  65     }
  66     if (file1_len > file2_len) {
  67       return 1;
  68     }
  69     assert(file1_len == file2_len, "invariant");
  70     cmp = strncmp(*file1, *file2, file1_len);
  71   }
  72   assert(cmp != 0, "invariant");


  92 static void date_time(char* buffer, size_t buffer_len) {
  93   assert(buffer != NULL, "invariant");
  94   assert(buffer_len >= iso8601_len, "buffer too small");
  95   os::iso8601_time(buffer, buffer_len);
  96   assert(strlen(buffer) >= iso8601_len + 1, "invariant");
  97   // "YYYY-MM-DDTHH:MM:SS"
  98   buffer[iso8601_len] = '\0';
  99   iso8601_to_date_time(buffer);
 100 }
 101 
 102 static int64_t file_size(fio_fd fd) {
 103   assert(fd != invalid_fd, "invariant");
 104   const int64_t current_offset = os::current_file_offset(fd);
 105   const int64_t size = os::lseek(fd, 0, SEEK_END);
 106   os::seek_to_file_offset(fd, current_offset);
 107   return size;
 108 }
 109 
 110 class RepositoryIterator : public StackObj {
 111  private:
 112   const char* const _repo;
 113   const size_t _repository_len;
 114   GrowableArray<const char*>* _files;
 115   const char* const fully_qualified(const char* entry) const;
 116   mutable int _iterator;
 117 

 118  public:
 119   RepositoryIterator(const char* repository, size_t repository_len);
 120   ~RepositoryIterator() {}
 121   const char* const filter(const char* entry) const;
 122   bool has_next() const;
 123   const char* const next() const;
 124 };
 125 
 126 const char* const RepositoryIterator::fully_qualified(const char* entry) const {
 127   assert(NULL != entry, "invariant");
 128   char* file_path_entry = NULL;
 129   // only use files that have content, not placeholders
 130   const char* const file_separator = os::file_separator();
 131   if (NULL != file_separator) {
 132     const size_t entry_len = strlen(entry);
 133     const size_t file_separator_length = strlen(file_separator);
 134     const size_t file_path_entry_length = _repository_len + file_separator_length + entry_len;
 135     file_path_entry = NEW_RESOURCE_ARRAY_RETURN_NULL(char, file_path_entry_length + 1);
 136     if (NULL == file_path_entry) {
 137       return NULL;
 138     }
 139     int position = 0;
 140     position += jio_snprintf(&file_path_entry[position], _repository_len + 1, "%s", _repo);
 141     position += jio_snprintf(&file_path_entry[position], file_separator_length + 1, "%s", os::file_separator());
 142     position += jio_snprintf(&file_path_entry[position], entry_len + 1, "%s", entry);
 143     file_path_entry[position] = '\0';
 144     assert((size_t)position == file_path_entry_length, "invariant");
 145     assert(strlen(file_path_entry) == (size_t)position, "invariant");
 146   }
 147   return file_path_entry;
 148 }
 149 
 150 const char* const RepositoryIterator::filter(const char* entry) const {
 151   if (entry == NULL) {

 152     return NULL;
 153   }
 154   const size_t entry_len = strlen(entry);
 155   if (entry_len <= 2) {
 156     // for "." and ".."



 157     return NULL;
 158   }
 159   char* entry_name = NEW_RESOURCE_ARRAY_RETURN_NULL(char, entry_len + 1);
 160   if (entry_name == NULL) {
 161     return NULL;
 162   }
 163   strncpy(entry_name, entry, entry_len + 1);
 164   const char* const fully_qualified_path_entry = fully_qualified(entry_name);
 165   if (NULL == fully_qualified_path_entry) {
 166     return NULL;
 167   }
 168   const fio_fd entry_fd = open_exclusivly(fully_qualified_path_entry);
 169   if (invalid_fd == entry_fd) {

 170     return NULL;
 171   }
 172   const int64_t entry_size = file_size(entry_fd);
 173   os::close(entry_fd);
 174   if (0 == entry_size) {
 175     return NULL;
 176   }
 177   return entry_name;

 178 }
 179 
 180 RepositoryIterator::RepositoryIterator(const char* repository, size_t repository_len) :
 181   _repo(repository),
 182   _repository_len(repository_len),
 183   _files(NULL),
 184   _iterator(0) {
 185   if (NULL != _repo) {
 186     assert(strlen(_repo) == _repository_len, "invariant");
 187     _files = new GrowableArray<const char*>(10);
 188     DIR* dirp = os::opendir(_repo);
 189     if (dirp == NULL) {
 190       log_error(jfr, system)("Unable to open repository %s", _repo);









 191       return;
 192     }






 193     struct dirent* dentry;
 194     while ((dentry = os::readdir(dirp)) != NULL) {
 195       const char* const entry_path = filter(dentry->d_name);
 196       if (NULL != entry_path) {
 197         _files->append(entry_path);
 198       }
 199     }
 200     os::closedir(dirp);
 201     if (_files->length() > 1) {
 202       _files->sort(file_sort);







 203     }

 204   }
 205 }
 206 
 207 bool RepositoryIterator::has_next() const {
 208   return (_files != NULL && _iterator < _files->length());
 209 }
 210 
 211 const char* const RepositoryIterator::next() const {
 212   return _iterator >= _files->length() ? NULL : fully_qualified(_files->at(_iterator++));
 213 }
 214 
 215 static void write_emergency_file(fio_fd emergency_fd, const RepositoryIterator& iterator) {
 216   assert(emergency_fd != invalid_fd, "invariant");
 217   const size_t size_of_file_copy_block = 1 * M; // 1 mb
 218   jbyte* const file_copy_block = NEW_RESOURCE_ARRAY_RETURN_NULL(jbyte, size_of_file_copy_block);
 219   if (file_copy_block == NULL) {
 220     return;
 221   }
 222   while (iterator.has_next()) {
 223     fio_fd current_fd = invalid_fd;
 224     const char* const fqn = iterator.next();
 225     if (fqn != NULL) {
 226       current_fd = open_exclusivly(fqn);
 227       if (current_fd != invalid_fd) {
 228         const int64_t current_filesize = file_size(current_fd);
 229         assert(current_filesize > 0, "invariant");
 230         int64_t bytes_read = 0;
 231         int64_t bytes_written = 0;
 232         while (bytes_read < current_filesize) {
 233           const ssize_t read_result = os::read_at(current_fd, file_copy_block, size_of_file_copy_block, bytes_read);
 234           if (-1 == read_result) {
 235             log_info(jfr)( // For user, should not be "jfr, system"
 236               "Unable to recover JFR data");
 237             break;
 238           }
 239           bytes_read += (int64_t)read_result;
 240           assert(bytes_read - bytes_written <= (int64_t)size_of_file_copy_block, "invariant");
 241           bytes_written += (int64_t)os::write(emergency_fd, file_copy_block, bytes_read - bytes_written);
 242           assert(bytes_read == bytes_written, "invariant");
 243         }
 244         os::close(current_fd);
 245       }
 246     }
 247   }
 248 }
 249 
 250 static const char* create_emergency_dump_path() {
 251   char* buffer = NEW_RESOURCE_ARRAY_RETURN_NULL(char, JVM_MAXPATHLEN);
 252   if (NULL == buffer) {
 253     return NULL;
 254   }
 255   const char* const cwd = os::get_current_directory(buffer, JVM_MAXPATHLEN);
 256   if (NULL == cwd) {
 257     return NULL;
 258   }
 259   size_t pos = strlen(cwd);
 260   const int fsep_len = jio_snprintf(&buffer[pos], JVM_MAXPATHLEN - pos, "%s", os::file_separator());
 261   const char* filename_fmt = NULL;
 262   // fetch specific error cause
 263   switch (JfrJavaSupport::cause()) {
 264     case JfrJavaSupport::OUT_OF_MEMORY:
 265       filename_fmt = vm_oom_filename_fmt;
 266       break;
 267     case JfrJavaSupport::STACK_OVERFLOW:
 268       filename_fmt = vm_soe_filename_fmt;
 269       break;
 270     default:
 271       filename_fmt = vm_error_filename_fmt;
 272   }
 273   char* emergency_dump_path = NULL;
 274   pos += fsep_len;
 275   if (Arguments::copy_expand_pid(filename_fmt, strlen(filename_fmt), &buffer[pos], JVM_MAXPATHLEN - pos)) {
 276     const size_t emergency_filename_length = strlen(buffer);
 277     emergency_dump_path = NEW_RESOURCE_ARRAY_RETURN_NULL(char, emergency_filename_length + 1);
 278     if (NULL == emergency_dump_path) {
 279       return NULL;
 280     }
 281     strncpy(emergency_dump_path, buffer, emergency_filename_length + 1);
 282   }
 283   if (emergency_dump_path != NULL) {
 284     log_info(jfr)( // For user, should not be "jfr, system"
 285       "Attempting to recover JFR data, emergency jfr file: %s", emergency_dump_path);







 286   }
 287   return emergency_dump_path;
 288 }
 289 
 290 // Caller needs ResourceMark
 291 static const char* create_emergency_chunk_path(const char* repository_path) {
 292   assert(repository_path != NULL, "invariant");
 293   const size_t repository_path_len = strlen(repository_path);
 294   // date time
 295   char date_time_buffer[32] = { 0 };
 296   date_time(date_time_buffer, sizeof(date_time_buffer));
 297   size_t date_time_len = strlen(date_time_buffer);
 298   size_t chunkname_max_len = repository_path_len          // repository_base_path
 299                              + 1                          // "/"
 300                              + date_time_len              // date_time
 301                              + strlen(chunk_file_jfr_ext) // .jfr
 302                              + 1;
 303   char* chunk_path = NEW_RESOURCE_ARRAY_RETURN_NULL(char, chunkname_max_len);
 304   if (chunk_path == NULL) {
 305     return NULL;
 306   }
 307   // append the individual substrings
 308   jio_snprintf(chunk_path, chunkname_max_len, "%s%s%s%s", repository_path, os::file_separator(), date_time_buffer, chunk_file_jfr_ext);
 309   return chunk_path;
 310 }
 311 
 312 static fio_fd emergency_dump_file_descriptor() {
 313   ResourceMark rm;
 314   const char* const emergency_dump_path = create_emergency_dump_path();
 315   return emergency_dump_path != NULL ? open_exclusivly(emergency_dump_path) : invalid_fd;
 316 }
 317 
 318 const char* JfrEmergencyDump::build_dump_path(const char* repository_path) {
 319   return repository_path == NULL ? create_emergency_dump_path() : create_emergency_chunk_path(repository_path);
 320 }
 321 
 322 void JfrEmergencyDump::on_vm_error(const char* repository_path) {
 323   assert(repository_path != NULL, "invariant");
 324   ResourceMark rm;
 325   const fio_fd emergency_fd = emergency_dump_file_descriptor();
 326   if (emergency_fd != invalid_fd) {
 327     RepositoryIterator iterator(repository_path, strlen(repository_path));
 328     write_emergency_file(emergency_fd, iterator);
 329     os::close(emergency_fd);
 330   }

 331 }
 332 
 333 /*
 334 * We are just about to exit the VM, so we will be very aggressive
 335 * at this point in order to increase overall success of dumping jfr data.
 336 *
 337 * If we end up deadlocking in the attempt of dumping out jfr data,
 338 * we rely on the WatcherThread task "is_error_reported()",
 339 * to exit the VM after a hard-coded timeout (disallow WatcherThread to emergency dump).
 340 * This "safety net" somewhat explains the aggressiveness in this attempt.
 341 *
 342 */
 343 static bool prepare_for_emergency_dump(Thread* thread) {
 344   assert(thread != NULL, "invariant");
 345 
 346   if (thread->is_Watcher_thread()) {
 347     // need WatcherThread as a safeguard against potential deadlocks
 348     return false;
 349   }
 350   if (JfrStream_lock->owned_by_self()) {


 426   JavaThread* const _jt;
 427   JavaThreadState _original_state;
 428  public:
 429 
 430   JavaThreadInVM(Thread* t) : _jt(t->is_Java_thread() ? (JavaThread*)t : NULL),
 431                               _original_state(_thread_max_state) {
 432     if ((_jt != NULL) && (_jt->thread_state() != _thread_in_vm)) {
 433       _original_state = _jt->thread_state();
 434       _jt->set_thread_state(_thread_in_vm);
 435     }
 436   }
 437 
 438   ~JavaThreadInVM() {
 439     if (_original_state != _thread_max_state) {
 440       _jt->set_thread_state(_original_state);
 441     }
 442   }
 443 
 444 };
 445 















 446 void JfrEmergencyDump::on_vm_shutdown(bool exception_handler) {
 447   if (!guard_reentrancy()) {
 448     return;
 449   }
 450 
 451   Thread* thread = Thread::current_or_null_safe();
 452   if (thread == NULL) {
 453     return;
 454   }
 455   // Ensure a JavaThread is _thread_in_vm when we make this call
 456   JavaThreadInVM jtivm(thread);
 457   if (!prepare_for_emergency_dump(thread)) {
 458     return;
 459   }
 460 
 461   EventDumpReason event;
 462   if (event.should_commit()) {
 463     event.set_reason(exception_handler ? "Crash" : "Out of Memory");
 464     event.set_recordingId(-1);
 465     event.commit();
 466   }
 467   if (!exception_handler) {
 468     // OOM
 469     LeakProfiler::emit_events(max_jlong, false);
 470   }
 471   const int messages = MSGBIT(MSG_VM_ERROR);
 472   JfrRecorderService service;
 473   service.rotate(messages);
 474 }
   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 "jfr/jfrEvents.hpp"
  27 #include "jfr/jni/jfrJavaSupport.hpp"
  28 #include "jfr/leakprofiler/leakProfiler.hpp"
  29 #include "jfr/recorder/repository/jfrEmergencyDump.hpp"
  30 #include "jfr/recorder/service/jfrPostBox.hpp"
  31 #include "jfr/recorder/service/jfrRecorderService.hpp"
  32 #include "jfr/utilities/jfrTypes.hpp"
  33 #include "logging/log.hpp"

  34 #include "runtime/atomic.hpp"

  35 #include "runtime/globals.hpp"
  36 #include "runtime/mutexLocker.hpp"
  37 #include "runtime/os.hpp"
  38 #include "runtime/thread.inline.hpp"
  39 #include "utilities/growableArray.hpp"
  40 #include "utilities/ostream.hpp"
  41 
  42 static const char vm_error_filename_fmt[] = "hs_err_pid%p.jfr";
  43 static const char vm_oom_filename_fmt[] = "hs_oom_pid%p.jfr";
  44 static const char vm_soe_filename_fmt[] = "hs_soe_pid%p.jfr";
  45 static const char chunk_file_jfr_ext[] = ".jfr";
  46 static const size_t iso8601_len = 19; // "YYYY-MM-DDTHH:MM:SS"
  47 static fio_fd emergency_fd = invalid_fd;
  48 static const int64_t chunk_file_header_size = 68;
  49 static const size_t chunk_file_extension_length = sizeof chunk_file_jfr_ext - 1;
  50 
  51 /*
  52  * The emergency dump logic is restrictive when it comes to
  53  * using internal VM constructs such as ResourceArea / Handle / Arena.
  54  * The reason being that the thread context is unknown.
  55  *
  56  * A single static buffer of size JVM_MAXPATHLEN is used for building paths.
  57  * os::malloc / os::free are used in a few places.
  58  */
  59 
  60 static char _path_buffer[JVM_MAXPATHLEN] = { 0 };
  61 
  62 static bool is_path_empty() {
  63   return *_path_buffer == '\0';
  64 }
  65 
  66 // returns with an appended file separator (if successful)
  67 static size_t get_current_directory() {
  68   if (os::get_current_directory(_path_buffer, sizeof(_path_buffer)) == NULL) {
  69     return 0;
  70   }
  71   const size_t cwd_len = strlen(_path_buffer);
  72   const int result = jio_snprintf(_path_buffer + cwd_len,
  73                                   sizeof(_path_buffer),
  74                                   "%s",
  75                                   os::file_separator());
  76   return (result == -1) ? 0 : strlen(_path_buffer);
  77 }
  78 
  79 static fio_fd open_exclusivly(const char* path) {
  80   assert((path != NULL) && (*path != '\0'), "invariant");
  81   return os::open(path, O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
  82 }
  83 
  84 static bool is_emergency_dump_file_open() {
  85   return emergency_fd != invalid_fd;
  86 }
  87 
  88 static bool open_emergency_dump_fd(const char* path) {
  89   if (path == NULL) {
  90     return false;
  91   }
  92   assert(emergency_fd == invalid_fd, "invariant");
  93   emergency_fd = open_exclusivly(path);
  94   return emergency_fd != invalid_fd;
  95 }
  96 
  97 static void close_emergency_dump_file() {
  98   if (is_emergency_dump_file_open()) {
  99     os::close(emergency_fd);
 100   }
 101 }
 102 
 103 static const char* create_emergency_dump_path() {
 104   assert(is_path_empty(), "invariant");
 105 
 106   const size_t path_len = get_current_directory();
 107   if (path_len == 0) {
 108     return NULL;
 109   }
 110   const char* filename_fmt = NULL;
 111   // fetch specific error cause
 112   switch (JfrJavaSupport::cause()) {
 113     case JfrJavaSupport::OUT_OF_MEMORY:
 114       filename_fmt = vm_oom_filename_fmt;
 115       break;
 116     case JfrJavaSupport::STACK_OVERFLOW:
 117       filename_fmt = vm_soe_filename_fmt;
 118       break;
 119     default:
 120       filename_fmt = vm_error_filename_fmt;
 121   }
 122   const bool result = Arguments::copy_expand_pid(filename_fmt, strlen(filename_fmt), _path_buffer + path_len, JVM_MAXPATHLEN - path_len);
 123   return result ? _path_buffer : NULL;
 124 }
 125 
 126 static bool open_emergency_dump_file() {
 127   if (is_emergency_dump_file_open()) {
 128     // opened already
 129     return true;
 130   }
 131   return open_emergency_dump_fd(create_emergency_dump_path());
 132 }
 133 
 134 static void report(outputStream* st, bool emergency_file_opened, const char* repository_path) {
 135   assert(st != NULL, "invariant");
 136   if (emergency_file_opened) {
 137     st->print_raw("# JFR recording file will be written. Location: ");
 138     st->print_raw_cr(_path_buffer);
 139     st->print_raw_cr("#");
 140   } else if (repository_path != NULL) {
 141     st->print_raw("# The JFR repository may contain useful JFR files. Location: ");
 142     st->print_raw_cr(repository_path);
 143     st->print_raw_cr("#");
 144   } else if (!is_path_empty()) {
 145     st->print_raw("# Unable to create a JFR recording file at location: ");
 146     st->print_raw_cr(_path_buffer);
 147     st->print_raw_cr("#");
 148   }
 149 }
 150 
 151 void JfrEmergencyDump::on_vm_error_report(outputStream* st, const char* repository_path) {
 152   assert(st != NULL, "invariant");
 153   Thread* thread = Thread::current_or_null_safe();
 154   if (thread != NULL) {
 155     report(st, open_emergency_dump_file(), repository_path);
 156   } else if (repository_path != NULL) {
 157     // a non-attached thread will not be able to write anything later
 158     report(st, false, repository_path);
 159   }
 160 }
 161 
 162 static int file_sort(const char** const file1, const char** file2) {
 163   assert(NULL != *file1 && NULL != *file2, "invariant");
 164   int cmp = strncmp(*file1, *file2, iso8601_len);
 165   if (0 == cmp) {
 166     const char* const dot1 = strchr(*file1, '.');
 167     assert(NULL != dot1, "invariant");
 168     const char* const dot2 = strchr(*file2, '.');
 169     assert(NULL != dot2, "invariant");
 170     ptrdiff_t file1_len = dot1 - *file1;
 171     ptrdiff_t file2_len = dot2 - *file2;
 172     if (file1_len < file2_len) {
 173       return -1;
 174     }
 175     if (file1_len > file2_len) {
 176       return 1;
 177     }
 178     assert(file1_len == file2_len, "invariant");
 179     cmp = strncmp(*file1, *file2, file1_len);
 180   }
 181   assert(cmp != 0, "invariant");


 201 static void date_time(char* buffer, size_t buffer_len) {
 202   assert(buffer != NULL, "invariant");
 203   assert(buffer_len >= iso8601_len, "buffer too small");
 204   os::iso8601_time(buffer, buffer_len);
 205   assert(strlen(buffer) >= iso8601_len + 1, "invariant");
 206   // "YYYY-MM-DDTHH:MM:SS"
 207   buffer[iso8601_len] = '\0';
 208   iso8601_to_date_time(buffer);
 209 }
 210 
 211 static int64_t file_size(fio_fd fd) {
 212   assert(fd != invalid_fd, "invariant");
 213   const int64_t current_offset = os::current_file_offset(fd);
 214   const int64_t size = os::lseek(fd, 0, SEEK_END);
 215   os::seek_to_file_offset(fd, current_offset);
 216   return size;
 217 }
 218 
 219 class RepositoryIterator : public StackObj {
 220  private:
 221   GrowableArray<const char*>* _file_names;
 222   int _path_buffer_file_name_offset;


 223   mutable int _iterator;
 224   const char* fully_qualified(const char* file_name) const;
 225   const char* filter(const char* file_name) const;
 226  public:
 227   RepositoryIterator(const char* repository_path);
 228   ~RepositoryIterator();

 229   bool has_next() const;
 230   const char* next() const;
 231 };
 232 
 233 // append the file_name at the _path_buffer_file_name_offset position
 234 const char* RepositoryIterator::fully_qualified(const char* file_name) const {
 235   assert(NULL != file_name, "invariant");
 236   assert(!is_path_empty(), "invariant");
 237   assert(_path_buffer_file_name_offset != 0, "invariant");
 238 
 239   const int result = jio_snprintf(_path_buffer + _path_buffer_file_name_offset,
 240                                   sizeof(_path_buffer) - _path_buffer_file_name_offset,
 241                                   "%s",
 242                                   file_name);
 243   return result != -1 ? _path_buffer : NULL;











 244 }
 245 
 246 // caller responsible for deallocation
 247 const char* RepositoryIterator::filter(const char* file_name) const {
 248   if (file_name == NULL) {
 249     return NULL;
 250   }
 251   const size_t len = strlen(file_name);
 252   if ((len < chunk_file_extension_length) ||
 253       (strncmp(&file_name[len - chunk_file_extension_length],
 254                chunk_file_jfr_ext,
 255                chunk_file_extension_length) != 0)) {
 256     // not a .jfr file
 257     return NULL;
 258   }
 259   const char* fqn = fully_qualified(file_name);
 260   if (fqn == NULL) {
 261     return NULL;
 262   }
 263   const fio_fd fd = open_exclusivly(fqn);
 264   if (invalid_fd == fd) {

 265     return NULL;
 266   }
 267   const int64_t size = file_size(fd);
 268   os::close(fd);
 269   if (size <= chunk_file_header_size) {
 270     return NULL;
 271   }
 272   char* const file_name_copy = (char*)os::malloc(len + 1, mtTracing);
 273   if (file_name_copy == NULL) {
 274     log_error(jfr, system)("Unable to malloc memory during jfr emergency dump");
 275     return NULL;
 276   }
 277   strncpy(file_name_copy, file_name, len + 1);
 278   return file_name_copy;
 279 }
 280 
 281 RepositoryIterator::RepositoryIterator(const char* repository_path) :
 282   _file_names(NULL),
 283   _path_buffer_file_name_offset(0),

 284   _iterator(0) {
 285     DIR* dirp = os::opendir(repository_path);



 286     if (dirp == NULL) {
 287       log_error(jfr, system)("Unable to open repository %s", repository_path);
 288       return;
 289     }
 290     // store repository path in the path buffer and save that position
 291     _path_buffer_file_name_offset = jio_snprintf(_path_buffer,
 292                                                  sizeof(_path_buffer),
 293                                                  "%s%s",
 294                                                  repository_path,
 295                                                  os::file_separator());
 296     if (_path_buffer_file_name_offset == -1) {
 297       return;
 298     }
 299     _file_names = new (ResourceObj::C_HEAP, mtTracing) GrowableArray<const char*>(10, true, mtTracing);
 300     if (_file_names == NULL) {
 301       log_error(jfr, system)("Unable to malloc memory during jfr emergency dump");
 302       return;
 303     }
 304     // iterate files in the repository and append filtered file names to the files array
 305     struct dirent* dentry;
 306     while ((dentry = os::readdir(dirp)) != NULL) {
 307       const char* file_name = filter(dentry->d_name);
 308       if (file_name != NULL) {
 309         _file_names->append(file_name);
 310       }
 311     }
 312     os::closedir(dirp);
 313     if (_file_names->length() > 1) {
 314       _file_names->sort(file_sort);
 315     }
 316 }
 317 
 318 RepositoryIterator::~RepositoryIterator() {
 319   if (_file_names != NULL) {
 320     for (int i = 0; i < _file_names->length(); ++i) {
 321       os::free(const_cast<char*>(_file_names->at(i)));
 322     }
 323     delete _file_names;
 324   }
 325 }
 326 
 327 bool RepositoryIterator::has_next() const {
 328   return _file_names != NULL && _iterator < _file_names->length();
 329 }
 330 
 331 const char* RepositoryIterator::next() const {
 332   return _iterator >= _file_names->length() ? NULL : fully_qualified(_file_names->at(_iterator++));
 333 }
 334 
 335 static void write_repository_files(const RepositoryIterator& iterator, char* const copy_block, size_t block_size) {
 336   assert(is_emergency_dump_file_open(), "invariant");





 337   while (iterator.has_next()) {
 338     fio_fd current_fd = invalid_fd;
 339     const char* const fqn = iterator.next();
 340     assert(fqn != NULL, "invariant");
 341     current_fd = open_exclusivly(fqn);
 342     if (current_fd != invalid_fd) {
 343       const int64_t size = file_size(current_fd);
 344       assert(size > 0, "invariant");
 345       int64_t bytes_read = 0;
 346       int64_t bytes_written = 0;
 347       while (bytes_read < size) {
 348         const ssize_t read_result = os::read_at(current_fd, copy_block, (int)block_size, bytes_read);
 349         if (-1 == read_result) {
 350           log_info(jfr)( // For user, should not be "jfr, system"
 351               "Unable to recover JFR data");
 352           break;
 353         }
 354         bytes_read += (int64_t)read_result;
 355         assert(bytes_read - bytes_written <= (int64_t)block_size, "invariant");
 356         bytes_written += (int64_t)os::write(emergency_fd, copy_block, bytes_read - bytes_written);
 357         assert(bytes_read == bytes_written, "invariant");
 358       }
 359       os::close(current_fd);
 360     }
 361   }

 362 }
 363 
 364 static void write_emergency_dump_file(const RepositoryIterator& iterator) {
 365   static const size_t block_size = 1 * M; // 1 mb
 366   char* const copy_block = (char*)os::malloc(block_size, mtTracing);
 367   if (copy_block == NULL) {
 368     log_error(jfr, system)("Unable to malloc memory during jfr emergency dump");
 369     log_error(jfr, system)("Unable to write jfr emergency dump file");


























 370   }
 371   write_repository_files(iterator, copy_block, block_size);
 372   os::free(copy_block);
 373 }
 374 
 375 void JfrEmergencyDump::on_vm_error(const char* repository_path) {
 376   assert(repository_path != NULL, "invariant");
 377   if (open_emergency_dump_file()) {
 378     RepositoryIterator iterator(repository_path);
 379     write_emergency_dump_file(iterator);
 380     close_emergency_dump_file();
 381   }

 382 }
 383 

 384 static const char* create_emergency_chunk_path(const char* repository_path) {

 385   const size_t repository_path_len = strlen(repository_path);

 386   char date_time_buffer[32] = { 0 };
 387   date_time(date_time_buffer, sizeof(date_time_buffer));










 388   // append the individual substrings
 389   const int result = jio_snprintf(_path_buffer,
 390                                   JVM_MAXPATHLEN,
 391                                   "%s%s%s%s",
 392                                   repository_path,
 393                                   os::file_separator(),
 394                                   date_time_buffer,
 395                                   chunk_file_jfr_ext);
 396   return result == -1 ? NULL : _path_buffer;
 397 }
 398 
 399 const char* JfrEmergencyDump::chunk_path(const char* repository_path) {
 400   if (repository_path == NULL) {
 401     if (!open_emergency_dump_file()) {
 402       return NULL;
 403     }
 404     // We can directly use the emergency dump file name as the chunk.
 405     // The chunk writer will open its own fd so we close this descriptor.
 406     close_emergency_dump_file();
 407     assert(!is_path_empty(), "invariant");
 408     return _path_buffer;


 409   }
 410   return create_emergency_chunk_path(repository_path);
 411 }
 412 
 413 /*
 414 * We are just about to exit the VM, so we will be very aggressive
 415 * at this point in order to increase overall success of dumping jfr data.
 416 *
 417 * If we end up deadlocking in the attempt of dumping out jfr data,
 418 * we rely on the WatcherThread task "is_error_reported()",
 419 * to exit the VM after a hard-coded timeout (disallow WatcherThread to emergency dump).
 420 * This "safety net" somewhat explains the aggressiveness in this attempt.
 421 *
 422 */
 423 static bool prepare_for_emergency_dump(Thread* thread) {
 424   assert(thread != NULL, "invariant");
 425 
 426   if (thread->is_Watcher_thread()) {
 427     // need WatcherThread as a safeguard against potential deadlocks
 428     return false;
 429   }
 430   if (JfrStream_lock->owned_by_self()) {


 506   JavaThread* const _jt;
 507   JavaThreadState _original_state;
 508  public:
 509 
 510   JavaThreadInVM(Thread* t) : _jt(t->is_Java_thread() ? (JavaThread*)t : NULL),
 511                               _original_state(_thread_max_state) {
 512     if ((_jt != NULL) && (_jt->thread_state() != _thread_in_vm)) {
 513       _original_state = _jt->thread_state();
 514       _jt->set_thread_state(_thread_in_vm);
 515     }
 516   }
 517 
 518   ~JavaThreadInVM() {
 519     if (_original_state != _thread_max_state) {
 520       _jt->set_thread_state(_original_state);
 521     }
 522   }
 523 
 524 };
 525 
 526 static void post_events(bool exception_handler) {
 527   if (exception_handler) {
 528     EventShutdown e;
 529     e.set_reason("VM Error");
 530     e.commit();
 531   } else {
 532     // OOM
 533     LeakProfiler::emit_events(max_jlong, false);
 534   }
 535   EventDumpReason event;
 536   event.set_reason(exception_handler ? "Crash" : "Out of Memory");
 537   event.set_recordingId(-1);
 538   event.commit();
 539 }
 540 
 541 void JfrEmergencyDump::on_vm_shutdown(bool exception_handler) {
 542   if (!guard_reentrancy()) {
 543     return;
 544   }

 545   Thread* thread = Thread::current_or_null_safe();
 546   if (thread == NULL) {
 547     return;
 548   }
 549   // Ensure a JavaThread is _thread_in_vm when we make this call
 550   JavaThreadInVM jtivm(thread);
 551   if (!prepare_for_emergency_dump(thread)) {
 552     return;
 553   }
 554   post_events(exception_handler);










 555   const int messages = MSGBIT(MSG_VM_ERROR);
 556   JfrRecorderService service;
 557   service.rotate(messages);
 558 }
< prev index next >