forked from cms-sw/cmssw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInitRootHandlers.cc
584 lines (511 loc) · 20.2 KB
/
InitRootHandlers.cc
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#include "FWCore/Services/src/InitRootHandlers.h"
#include "FWCore/ServiceRegistry/interface/ActivityRegistry.h"
#include "DataFormats/Common/interface/RefCoreStreamer.h"
#include "FWCore/MessageLogger/interface/ELseverityLevel.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/PluginManager/interface/PluginCapabilities.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/Utilities/interface/EDMException.h"
#include "FWCore/Utilities/interface/TypeWithDict.h"
#include "FWCore/Utilities/interface/UnixSignalHandlers.h"
#include <thread>
#include <sys/wait.h>
#include <sstream>
#include <string.h>
#include "TROOT.h"
#include "TError.h"
#include "TFile.h"
#include "TInterpreter.h"
#include "TH1.h"
#include "TSystem.h"
#include "TUnixSystem.h"
#include "TTree.h"
#include "TVirtualStreamerInfo.h"
#include "TThread.h"
#include "TClassTable.h"
namespace edm {
namespace service {
int cmssw_stacktrace(void *);
}
}
namespace {
enum class SeverityLevel {
kInfo,
kWarning,
kError,
kSysError,
kFatal
};
static thread_local bool s_ignoreWarnings = false;
static bool s_ignoreEverything = false;
void RootErrorHandlerImpl(int level, char const* location, char const* message) {
bool die = false;
// Translate ROOT severity level to MessageLogger severity level
SeverityLevel el_severity = SeverityLevel::kInfo;
if (level >= kFatal) {
el_severity = SeverityLevel::kFatal;
} else if (level >= kSysError) {
el_severity = SeverityLevel::kSysError;
} else if (level >= kError) {
el_severity = SeverityLevel::kError;
} else if (level >= kWarning) {
el_severity = s_ignoreWarnings ? SeverityLevel::kInfo : SeverityLevel::kWarning;
}
if(s_ignoreEverything) {
el_severity = SeverityLevel::kInfo;
}
// Adapt C-strings to std::strings
// Arrange to report the error location as furnished by Root
std::string el_location = "@SUB=?";
if (location != 0) el_location = std::string("@SUB=")+std::string(location);
std::string el_message = "?";
if (message != 0) el_message = message;
// Try to create a meaningful id string using knowledge of ROOT error messages
//
// id == "ROOT-ClassName" where ClassName is the affected class
// else "ROOT/ClassName" where ClassName is the error-declaring class
// else "ROOT"
std::string el_identifier = "ROOT";
std::string precursor("class ");
size_t index1 = el_message.find(precursor);
if (index1 != std::string::npos) {
size_t index2 = index1 + precursor.length();
size_t index3 = el_message.find_first_of(" :", index2);
if (index3 != std::string::npos) {
size_t substrlen = index3-index2;
el_identifier += "-";
el_identifier += el_message.substr(index2,substrlen);
}
} else {
index1 = el_location.find("::");
if (index1 != std::string::npos) {
el_identifier += "/";
el_identifier += el_location.substr(0, index1);
}
}
// Intercept some messages and upgrade the severity
if ((el_location.find("TBranchElement::Fill") != std::string::npos)
&& (el_message.find("fill branch") != std::string::npos)
&& (el_message.find("address") != std::string::npos)
&& (el_message.find("not set") != std::string::npos)) {
el_severity = SeverityLevel::kFatal;
}
if ((el_message.find("Tree branches") != std::string::npos)
&& (el_message.find("different numbers of entries") != std::string::npos)) {
el_severity = SeverityLevel::kFatal;
}
// Intercept some messages and downgrade the severity
if ((el_message.find("no dictionary for class") != std::string::npos) ||
(el_message.find("already in TClassTable") != std::string::npos) ||
(el_message.find("matrix not positive definite") != std::string::npos) ||
(el_message.find("not a TStreamerInfo object") != std::string::npos) ||
(el_message.find("Problems declaring payload") != std::string::npos) ||
(el_message.find("Announced number of args different from the real number of argument passed") != std::string::npos) || // Always printed if gDebug>0 - regardless of whether warning message is real.
(el_location.find("Fit") != std::string::npos) ||
(el_location.find("TDecompChol::Solve") != std::string::npos) ||
(el_location.find("THistPainter::PaintInit") != std::string::npos) ||
(el_location.find("TUnixSystem::SetDisplay") != std::string::npos) ||
(el_location.find("TGClient::GetFontByName") != std::string::npos) ||
(el_message.find("nbins is <=0 - set to nbins = 1") != std::string::npos) ||
(el_message.find("nbinsy is <=0 - set to nbinsy = 1") != std::string::npos) ||
(level < kError and
(el_location.find("CINTTypedefBuilder::Setup")!= std::string::npos) and
(el_message.find("possible entries are in use!") != std::string::npos))) {
el_severity = SeverityLevel::kInfo;
}
if (el_severity == SeverityLevel::kInfo) {
// Don't throw if the message is just informational.
die = false;
} else {
die = true;
}
// Feed the message to the MessageLogger and let it choose to suppress or not.
// Root has declared a fatal error. Throw an EDMException unless the
// message corresponds to a pending signal. In that case, do not throw
// but let the OS deal with the signal in the usual way.
if (die && (el_location != std::string("@SUB=TUnixSystem::DispatchSignals"))) {
std::ostringstream sstr;
sstr << "Fatal Root Error: " << el_location << "\n" << el_message << '\n';
edm::Exception except(edm::errors::FatalRootError, sstr.str());
except.addAdditionalInfo(except.message());
except.clearMessage();
throw except;
}
// Typically, we get here only for informational messages,
// but we leave the other code in just in case we change
// the criteria for throwing.
if (el_severity == SeverityLevel::kFatal) {
edm::LogError("Root_Fatal") << el_location << el_message;
} else if (el_severity == SeverityLevel::kSysError) {
edm::LogError("Root_Severe") << el_location << el_message;
} else if (el_severity == SeverityLevel::kError) {
edm::LogError("Root_Error") << el_location << el_message;
} else if (el_severity == SeverityLevel::kWarning) {
edm::LogWarning("Root_Warning") << el_location << el_message ;
} else if (el_severity == SeverityLevel::kInfo) {
edm::LogInfo("Root_Information") << el_location << el_message ;
}
}
void RootErrorHandler(int level, bool, char const* location, char const* message) {
RootErrorHandlerImpl(level, location, message);
}
extern "C" {
static int full_write(int fd, const char *text)
{
const char *buffer = text;
size_t count = strlen(text);
ssize_t written = 0;
while (count)
{
written = write(fd, buffer, count);
if (written == -1)
{
if (errno == EINTR) {continue;}
else {return -errno;}
}
count -= written;
buffer += written;
}
return 0;
}
static int full_read(int fd, char *inbuf, size_t len)
{
char *buf = inbuf;
size_t count = len;
ssize_t complete = 0;
while (count)
{
complete = read(fd, buf, count);
if (complete == -1)
{
if (errno == EINTR) {continue;}
else {return -errno;}
}
count -= complete;
buf += complete;
}
return 0;
}
static int full_cerr_write(const char *text)
{
return full_write(2, text);
}
void sig_dostack_then_abort(int sig, siginfo_t*, void*) {
const char* signalname = "unknown";
switch (sig) {
case SIGBUS:
signalname = "bus error";
break;
case SIGSEGV:
signalname = "segmentation violation";
break;
case SIGILL:
signalname = "illegal instruction";
default:
break;
}
full_cerr_write("\n\nA fatal system signal has occurred: ");
full_cerr_write(signalname);
full_cerr_write("\nThe following is the call stack containing the origin of the signal.\n"
"NOTE:The first few functions on the stack are artifacts of processing the signal and can be ignored\n\n");
edm::service::InitRootHandlers::stacktraceFromThread();
full_cerr_write("\nA fatal system signal has occurred: ");
full_cerr_write(signalname);
full_cerr_write("\n");
// For these three known cases, re-raise the signal so get the correct
// exit code.
if ((sig == SIGILL) || (sig == SIGSEGV) || (sig == SIGBUS))
{
signal(sig, SIG_DFL);
raise(sig);
}
else
{
::abort();
}
}
void sig_abort(int sig, siginfo_t*, void*) {
::abort();
}
}
} // end of unnamed namespace
namespace edm {
namespace service {
/*
* We've run into issues where GDB fails to print the thread which calls clone().
* To avoid this problem, we have an alternate approach below where the signal handler
* only reads/writes to a dedicated thread via pipes. The helper thread does the clone()
* invocation; we don't care if that thread is missing from the traceback in this case.
*/
static void cmssw_stacktrace_fork();
void InitRootHandlers::stacktraceHelperThread()
{
int toParent = childToParent_[1];
int fromParent = parentToChild_[0];
char buf[2]; buf[1] = '\0';
while(true)
{
int result = full_read(fromParent, buf, 1);
if (result < 0)
{
close(toParent);
full_cerr_write("\n\nTraceback helper thread failed to read from parent: ");
full_cerr_write(strerror(-result));
full_cerr_write("\n");
::abort();
}
if (buf[0] == '1')
{
cmssw_stacktrace_fork();
full_write(toParent, buf);
}
else if (buf[0] == '2')
{
// We have just finished forking. Reload the file descriptors for thread
// communication.
close(toParent);
close(fromParent);
toParent = childToParent_[1];
fromParent = parentToChild_[0];
}
else if (buf[0] == '3')
{
break;
}
else
{
close(toParent);
full_cerr_write("\n\nTraceback helper thread got unknown command from parent: ");
full_cerr_write(buf);
full_cerr_write("\n");
::abort();
}
}
}
void InitRootHandlers::stacktraceFromThread()
{
int result = full_write(parentToChild_[1], "1");
if (result < 0)
{
full_cerr_write("\n\nAttempt to request stacktrace failed: ");
full_cerr_write(strerror(-result));
full_cerr_write("\n");
return;
}
char buf[2]; buf[1] = '\0';
if ((result = full_read(childToParent_[0], buf, 1)) < 0)
{
full_cerr_write("\n\nWaiting for stacktrace completion failed: ");
full_cerr_write(strerror(-result));
full_cerr_write("\n");
return;
}
}
void cmssw_stacktrace_fork()
{
char child_stack[4*1024];
char *child_stack_ptr = child_stack + 4*1024;
// On Linux, we currently use jemalloc. This registers pthread_atfork handlers; these
// handlers are *not* async-signal safe. Hence, a deadlock is possible if we invoke
// fork() from our signal handlers. Accordingly, we use clone (not POSIX, but AS-safe)
// as that is closer to the 'raw metal' syscall and avoids pthread_atfork handlers.
int pid =
#ifdef __linux__
clone(edm::service::cmssw_stacktrace, child_stack_ptr, CLONE_VM|CLONE_FS|SIGCHLD, nullptr);
#else
fork();
if (child_stack_ptr) {} // Suppress 'unused variable' warning on non-Linux
if (pid == 0) {edm::service::cmssw_stacktrace(nullptr); ::abort();}
#endif
if (pid == -1)
{
full_cerr_write("(Attempt to perform stack dump failed.)\n");
}
else
{
int status;
if (waitpid(pid, &status, 0) == -1)
{
full_cerr_write("(Failed to wait on stack dump output.)\n");
}
}
}
int cmssw_stacktrace(void * /*arg*/)
{
char *const *argv = edm::service::InitRootHandlers::getPstackArgv();
execv("/bin/sh", argv);
::abort();
return 1;
}
static char pstackName[] = "(CMSSW stack trace helper)";
static char dashC[] = "-c";
char InitRootHandlers::pidString_[InitRootHandlers::pidStringLength_] = {};
char * const InitRootHandlers::pstackArgv_[] = {pstackName, dashC, InitRootHandlers::pidString_, nullptr};
int InitRootHandlers::parentToChild_[2] = {-1, -1};
int InitRootHandlers::childToParent_[2] = {-1, -1};
std::unique_ptr<std::thread> InitRootHandlers::helperThread_;
InitRootHandlers::InitRootHandlers (ParameterSet const& pset, ActivityRegistry& iReg)
: RootHandlers(),
unloadSigHandler_(pset.getUntrackedParameter<bool> ("UnloadRootSigHandler")),
resetErrHandler_(pset.getUntrackedParameter<bool> ("ResetRootErrHandler")),
loadAllDictionaries_(pset.getUntrackedParameter<bool>("LoadAllDictionaries")),
autoLibraryLoader_(loadAllDictionaries_ or pset.getUntrackedParameter<bool> ("AutoLibraryLoader"))
{
if(unloadSigHandler_) {
// Deactivate all the Root signal handlers and restore the system defaults
gSystem->ResetSignal(kSigChild);
gSystem->ResetSignal(kSigBus);
gSystem->ResetSignal(kSigSegmentationViolation);
gSystem->ResetSignal(kSigIllegalInstruction);
gSystem->ResetSignal(kSigSystem);
gSystem->ResetSignal(kSigPipe);
gSystem->ResetSignal(kSigAlarm);
gSystem->ResetSignal(kSigUrgent);
gSystem->ResetSignal(kSigFloatingException);
gSystem->ResetSignal(kSigWindowChanged);
} else if(pset.getUntrackedParameter<bool>("AbortOnSignal")){
cachePidInfo();
//NOTE: ROOT can also be told to abort on these kinds of problems BUT
// it requires an TApplication to be instantiated which causes problems
gSystem->ResetSignal(kSigBus);
gSystem->ResetSignal(kSigSegmentationViolation);
gSystem->ResetSignal(kSigIllegalInstruction);
installCustomHandler(SIGBUS,sig_dostack_then_abort);
sigBusHandler_ = std::shared_ptr<const void>(nullptr,[](void*) {
installCustomHandler(SIGBUS,sig_abort);
});
installCustomHandler(SIGSEGV,sig_dostack_then_abort);
sigSegvHandler_ = std::shared_ptr<const void>(nullptr,[](void*) {
installCustomHandler(SIGSEGV,sig_abort);
});
installCustomHandler(SIGILL,sig_dostack_then_abort);
sigIllHandler_ = std::shared_ptr<const void>(nullptr,[](void*) {
installCustomHandler(SIGILL,sig_abort);
});
iReg.watchPostForkReacquireResources(this, &InitRootHandlers::cachePidInfoHandler);
}
if(resetErrHandler_) {
// Replace the Root error handler with one that uses the MessageLogger
SetErrorHandler(RootErrorHandler);
}
// Enable automatic Root library loading.
if(autoLibraryLoader_) {
gInterpreter->SetClassAutoloading(1);
}
// Set ROOT parameters.
TTree::SetMaxTreeSize(kMaxLong64);
TH1::AddDirectory(kFALSE);
//G__SetCatchException(0);
// Set custom streamers
setRefCoreStreamer();
// Load the library containing dictionaries for std:: classes, if not already loaded.
if (!hasDictionary(typeid(std::vector<std::vector<unsigned int> >))) {
TypeWithDict::byName("std::vector<std::vector<unsigned int> >");
}
int debugLevel = pset.getUntrackedParameter<int>("DebugLevel");
if(debugLevel >0) {
gDebug = debugLevel;
}
}
InitRootHandlers::~InitRootHandlers () {
// close all open ROOT files
TIter iter(gROOT->GetListOfFiles());
TObject *obj = nullptr;
while(nullptr != (obj = iter.Next())) {
TFile* f = dynamic_cast<TFile*>(obj);
if(f) {
// We get a new iterator each time,
// because closing a file can invalidate the iterator
f->Close();
iter = TIter(gROOT->GetListOfFiles());
}
}
}
void InitRootHandlers::willBeUsingThreads() {
//Tell Root we want to be multi-threaded
TThread::Initialize();
//When threading, also have to keep ROOT from logging all TObjects into a list
TObject::SetObjectStat(false);
//Have to avoid having Streamers modify themselves after they have been used
TVirtualStreamerInfo::Optimize(false);
}
void InitRootHandlers::initializeThisThreadForUse() {
static thread_local TThread guard;
}
void InitRootHandlers::fillDescriptions(ConfigurationDescriptions& descriptions) {
ParameterSetDescription desc;
desc.setComment("Centralized interface to ROOT.");
desc.addUntracked<bool>("UnloadRootSigHandler", false)
->setComment("If True, signals are handled by this service, rather than by ROOT.");
desc.addUntracked<bool>("ResetRootErrHandler", true)
->setComment("If True, ROOT messages (e.g. errors, warnings) are handled by this service, rather than by ROOT.");
desc.addUntracked<bool>("AutoLibraryLoader", true)
->setComment("If True, enables automatic loading of data dictionaries.");
desc.addUntracked<bool>("LoadAllDictionaries",false)
->setComment("If True, loads all ROOT dictionaries.");
desc.addUntracked<bool>("AbortOnSignal",true)
->setComment("If True, do an abort when a signal occurs that causes a crash. If False, ROOT will do an exit which attempts to do a clean shutdown.");
desc.addUntracked<int>("DebugLevel",0)
->setComment("Sets ROOT's gDebug value.");
descriptions.add("InitRootHandlers", desc);
}
char *const *
InitRootHandlers::getPstackArgv() {
return pstackArgv_;
}
void
InitRootHandlers::enableWarnings_() {
s_ignoreWarnings =false;
}
void
InitRootHandlers::ignoreWarnings_() {
s_ignoreWarnings = true;
}
void
InitRootHandlers::cachePidInfo()
{
if (snprintf(pidString_, pidStringLength_-1, "gdb -quiet -p %d 2>&1 <<EOF |\n"
"set width 0\n"
"set height 0\n"
"set pagination no\n"
"thread apply all bt\n"
"EOF\n"
"/bin/sed -n -e 's/^\\((gdb) \\)*//' -e '/^#/p' -e '/^Thread/p'", getpid()) >= pidStringLength_)
{
std::ostringstream sstr;
sstr << "Unable to pre-allocate stacktrace handler information";
edm::Exception except(edm::errors::OtherCMS, sstr.str());
throw except;
}
// These are initialized to -1; harmless to close an invalid FD.
// If this is called post-fork, we don't want to be communicating on
// these FDs as they are used internally by the parent.
close(childToParent_[0]);
close(childToParent_[1]);
childToParent_[0] = -1; childToParent_[1] = -1;
close(parentToChild_[0]);
close(parentToChild_[1]);
parentToChild_[0] = -1; parentToChild_[1] = -1;
if (-1 == pipe2(childToParent_, O_CLOEXEC))
{
std::ostringstream sstr;
sstr << "Failed to create child-to-parent pipes (errno=" << errno << "): " << strerror(errno);
edm::Exception except(edm::errors::OtherCMS, sstr.str());
throw except;
}
if (-1 == pipe2(parentToChild_, O_CLOEXEC))
{
close(childToParent_[0]); close(childToParent_[1]);
childToParent_[0] = -1; childToParent_[1] = -1;
std::ostringstream sstr;
sstr << "Failed to create child-to-parent pipes (errno=" << errno << "): " << strerror(errno);
edm::Exception except(edm::errors::OtherCMS, sstr.str());
throw except;
}
helperThread_.reset(new std::thread(stacktraceHelperThread));
helperThread_->detach();
}
} // end of namespace service
} // end of namespace edm