17#include <mach/mach_time.h>
18#include <mach-o/dyld.h>
20#include <objc/objc-runtime.h>
26#include <sys/sysctl.h>
31#include <CoreFoundation/CoreFoundation.h>
33#include <CoreGraphics/CoreGraphics.h>
34#include <CoreText/CoreText.h>
49 if (
auto ep = std::current_exception())
52 std::rethrow_exception(ep);
54 catch (std::exception
const &e)
57 const char *typeName =
typeid(e).name();
58 char *unmangled = abi::__cxa_demangle(typeName, 0, 0, &status);
62 VUserLog(
"Terminating due to uncaught %s: \"%s\"", typeName, e.what());
66 VUserLog(
"Terminating due to uncaught exception of unknown type");
71 VUserLog(
"Terminating because std::terminate was called (no exception data available)");
82 static mach_timebase_info_data_t info = {0,0};
85 kern_return_t ret = mach_timebase_info(&info);
86 if (ret != KERN_SUCCESS)
88 VUserLog(
"Failed to get mach timebase: %d", ret);
95 return (
double)mach_absolute_time() * info.numer / (info.denom * NSEC_PER_SEC);
115typedef std::map<std::string, VuoLogProfileEntry> VuoLogProfileType;
116static VuoLogProfileType *VuoLogProfile;
117static dispatch_queue_t VuoLogProfileQueue;
126static void __attribute__((constructor)) VuoLog_init(
void)
135 char executablePath[PATH_MAX + 1];
136 uint32_t size =
sizeof(executablePath);
137 if (!_NSGetExecutablePath(executablePath, &size))
141 VuoLogProfileQueue = dispatch_queue_create(
"VuoLogProfile", NULL);
142 VuoLogProfile =
new VuoLogProfileType;
146#if defined(VUO_PROFILE) || defined(DOXYGEN)
152 dispatch_sync(VuoLogProfileQueue, ^{
153 VuoLogProfileType::iterator i = VuoLogProfile->find(name);
154 if (i != VuoLogProfile->end())
156 i->second.total += time;
157 if (time < i->second.min)
158 i->second.min = time;
159 if (time > i->second.max)
160 i->second.max = time;
164 (*VuoLogProfile)[name] = (VuoLogProfileEntry){time, time, time, 1};
171extern "C" void __attribute__((destructor)) VuoLog_dumpProfile(
void)
173 dispatch_sync(VuoLogProfileQueue, ^{
175 for (VuoLogProfileType::iterator i = VuoLogProfile->begin(); i != VuoLogProfile->end(); ++i)
176 fprintf(stderr,
"%30s %12.9f s (%7.4f%%) (min %12.9f, max %12.9f, avg %12.9f, count %lld)\n",
179 i->second.total * 100. / totalRuntime,
182 i->second.total / i->second.count,
197#define VuoCrashReport_alignment __attribute__((aligned(8)))
214VuoCrashReport_infoType VuoCrashReport __attribute__((section(
"__DATA,__crash_info"))) = { 4, NULL, NULL, NULL, NULL, NULL, NULL };
216void VuoLog_statusF(
const char *moduleName,
const char *file,
const unsigned int linenumber,
const char *
function,
const char *format, ...)
218 static dispatch_once_t statusInitialized = 0;
219 static dispatch_queue_t statusQueue;
220 dispatch_once(&statusInitialized, ^{
221 statusQueue = dispatch_queue_create(
"VuoLogStatus", NULL);
224 char *message =
nullptr;
228 va_start(args, format);
229 vasprintf(&message, format, args);
233 dispatch_sync(statusQueue, ^{
234 if (VuoCrashReport.message2)
235 free(VuoCrashReport.message2);
238 VuoCrashReport.message2 = message;
240 VuoCrashReport.message2 =
nullptr;
259 Class NSProcessInfoClass = objc_getClass(
"NSProcessInfo");
260 id processInfo = ((id(*)(id, SEL))objc_msgSend)((
id)NSProcessInfoClass, sel_getUid(
"processInfo"));
263 operatingSystemVersionType operatingSystemVersionFunc = (operatingSystemVersionType)objc_msgSend_stret;
265 operatingSystemVersionType operatingSystemVersionFunc = (operatingSystemVersionType)objc_msgSend;
267 NSOperatingSystemVersion operatingSystemVersion = operatingSystemVersionFunc(processInfo, sel_getUid(
"operatingSystemVersion"));
268 return operatingSystemVersion;
284 mib[2] = KERN_PROC_PID;
287 struct kinfo_proc info;
288 info.kp_proc.p_flag = 0;
289 size_t size =
sizeof(info);
290 if (sysctl(mib,
sizeof(mib) /
sizeof(*mib), &info, &size, NULL, 0) == 0
291 && info.kp_proc.p_flag & P_TRACED)
297 uint32_t imageCount = _dyld_image_count();
298 for (uint32_t i = 0; i < imageCount; ++i)
299 if (strstr(_dyld_get_image_name(i),
"/DVTInstrumentsFoundation.framework/"))
306extern struct mach_header __dso_handle;
308void VuoLog(
const char *moduleName,
const char *file,
const unsigned int linenumber,
const char *
function,
const char *format, ...)
312 fprintf(stderr,
"VuoLog() error: Invalid 'moduleName' argument (%p). You may need to rebuild the module calling VuoLog().\n", moduleName);
318 fprintf(stderr,
"VuoLog() error: Invalid 'file' argument (%p). You may need to rebuild the module calling VuoLog().\n", file);
324 fprintf(stderr,
"VuoLog() error: Invalid 'function' argument (%p). You may need to rebuild the module calling VuoLog().\n",
function);
330 fprintf(stderr,
"VuoLog() error: Invalid 'format' argument (%p). You may need to rebuild the module calling VuoLog().\n", format);
337 va_start(args, format);
338 int size = vsnprintf(NULL, 0, format, args);
341 char *formattedString = (
char *)malloc(size+1);
342 va_start(args, format);
343 vsnprintf(formattedString, size+1, format, args);
346 char *formattedFunction = NULL;
350 if (
function &&
function[0] ==
'_' &&
function[1] ==
'_')
352 int actualFunctionLength = atoi(
function + 2);
353 if (actualFunctionLength)
354 formattedFunction = strndup(
function + 3 + (
int)log10(actualFunctionLength), actualFunctionLength);
356 formattedFunction = strndup(
function + 2, strrchr(
function + 2,
'_') - (
function + 2));
361 if (strncmp(formattedFunction,
"_ZN", 3) == 0)
364 int len, priorLen = 0;
365 while ((len = atoi(formattedFunction + pos)))
367 pos += 1 + (int)log10(len) + len;
370 char *f2 = strndup(formattedFunction + pos - priorLen, priorLen);
371 free(formattedFunction);
372 formattedFunction = f2;
377 const char *blockInvokePos = strstr(
function,
"_block_invoke");
379 formattedFunction = strndup(
function, blockInvokePos -
function);
385 const char *f = formattedFunction ? formattedFunction :
function;
386 size_t fLen = strlen(f);
387 if (f[fLen - 1] !=
']')
389 size_t mallocSize = fLen + 2 + 1;
390 char *f2 = (
char *)malloc(mallocSize);
391 strlcpy(f2, f, mallocSize);
392 strlcat(f2,
"()", mallocSize);
393 if (formattedFunction)
394 free(formattedFunction);
395 formattedFunction = f2;
399 const char *formattedFile = file;
402 formattedFile =
"(unknown)";
405 if (
const char *lastSlash = strrchr(formattedFile,
'/'))
406 formattedFile = lastSlash + 1;
411 static double priorTime = 0;
412 const char *separator =
"";
413 if (priorTime > 0 && time - priorTime > 0.5)
418 pthread_t thread = pthread_self();
419 char threadName[256];
421 strcpy(threadName,
"main");
424 bzero(threadName, 256);
425 int ret = pthread_getname_np(thread, threadName, 256);
426 if (!(ret == 0 && strlen(threadName)))
427 snprintf(threadName, 256,
"%llx", (uint64_t)thread);
431 const char *mainColor =
"\033[97m";
433 const char *metadataColor =
"\033[38;5;249m";
435 const char *separatorColor =
"\033[90m";
439 int pidColor = getpid() % 144 + 88;
443 : ((uint64_t)thread) % 144 + 88;
445 fprintf(stderr,
"%s%s[%s%8.3fs%s] %s%12.12s%s:%s%-12.12s %s[\033[38;5;%dm%5d%s:\033[38;5;%dm%-8.8s%s] %s%20.20s%s:%s%-4u %32.32s %s%s\033[0m\n",
455 moduleName ? moduleName :
"Vuo",
468 formattedFunction ? formattedFunction :
function,
478 typedef void (*vuoMacOsLogInternalType)(
void *dso,
void *log, uint8_t type,
const char *message, ...);
479 typedef void (*vuoMacOsLogImplType)(
void *dso,
void *log, uint8_t type,
const char *format, uint8_t *buf, uint32_t size);
480 static vuoMacOsLogInternalType vuoMacOsLogInternal = NULL;
481 static vuoMacOsLogImplType vuoMacOsLogImpl = NULL;
482 static dispatch_once_t once = 0;
483 static bool debuggerAttached =
false;
484 dispatch_once(&once, ^{
487 if (operatingSystemVersion.majorVersion == 10 && operatingSystemVersion.minorVersion == 12)
489 vuoMacOsLogInternal = (vuoMacOsLogInternalType)dlsym(RTLD_SELF,
"_os_log_internal");
490 else if ((operatingSystemVersion.majorVersion == 10 && operatingSystemVersion.minorVersion > 12)
491 || operatingSystemVersion.majorVersion > 10)
493 vuoMacOsLogImpl = (vuoMacOsLogImplType)dlsym(RTLD_SELF,
"_os_log_impl");
496 if (!debuggerAttached)
498 void *log = os_log_create(
"org.vuo", formattedFile);
500 if (vuoMacOsLogInternal)
501 vuoMacOsLogInternal(&__dso_handle, log, 0 ,
"%{public}41s:%-4u %{public}s", formattedFunction ? formattedFunction :
function, linenumber, formattedString);
502 else if (vuoMacOsLogImpl)
504 char *formattedForOsLog;
505 asprintf(&formattedForOsLog,
"%41s:%-4u %s", formattedFunction ? formattedFunction :
function, linenumber, formattedString);
508 uint8_t logFormatDescriptor[12] = {
515 memcpy(logFormatDescriptor + 4, &formattedForOsLog, 8);
517 vuoMacOsLogImpl(&__dso_handle, log, 0 ,
"%{public}s", logFormatDescriptor,
sizeof(logFormatDescriptor));
519 free(formattedForOsLog);
527 static dispatch_once_t historyInitialized = 0;
528 dispatch_once(&historyInitialized, ^{
537 char *formattedPrefixedString;
538 asprintf(&formattedPrefixedString,
"t=%8.4fs %27.27s:%-4u %41.41s %s", time, formattedFile, linenumber, formattedFunction ? formattedFunction :
function, formattedString);
539 free(formattedString);
540 if (formattedFunction)
541 free(formattedFunction);
563 if (VuoCrashReport.message)
564 free(VuoCrashReport.message);
572 char *message = (
char *)malloc(size);
577 strlcat(message,
"\n", size);
581 VuoCrashReport.message = message;
596 static dispatch_once_t checked = 0;
597 static bool debug =
false;
598 dispatch_once(&checked, ^{
599 debug = CFPreferencesGetAppBooleanValue(CFSTR(
"debug"), CFSTR(
"org.vuo.Editor"), NULL);
612 backtrace.erase(backtrace.begin());
615 for (
auto line : backtrace)
616 fprintf(stderr,
"%3d %s\n", i++, line.c_str());
626 size_t replacementLen = strlen(replacement);
628 regcomp(®ex, substringToRemove, REG_EXTENDED);
630 regmatch_t pmatch[nmatch];
631 while (!regexec(®ex, wholeString, nmatch, pmatch, 0))
633 strncpy(wholeString + pmatch[0].rm_so, replacement, replacementLen);
634 memmove(wholeString + pmatch[0].rm_so + replacementLen, wholeString + pmatch[0].rm_eo, strlen(wholeString + pmatch[0].rm_eo) + 1);
645 size_t size = backtrace(array, 100);
646 char **strings = backtrace_symbols(array, size);
647 vector<string> outputStrings;
650 for (
size_t i = 1; i < size; i++)
653 const int lineNumberLen = 4;
654 string trimmedLine = strings[i] + lineNumberLen;
656 const int libraryLen = 36;
657 const int addressLen = 19;
658 string symbol = strings[i] + lineNumberLen + libraryLen + addressLen;
659 string instructionOffset = symbol.substr(symbol.find(
' '));
660 symbol = symbol.substr(0, symbol.find(
' '));
663 char *unmangled = abi::__cxa_demangle(symbol.c_str(),
nullptr,
nullptr, &status);
668 VuoLog_replaceString(unmangled,
"basic_string<char, char_traits<char>, allocator<char> >",
"string");
673 outputStrings.push_back(trimmedLine.substr(0, libraryLen + addressLen) + unmangled + instructionOffset);
677 outputStrings.push_back(trimmedLine);
684 auto last = outputStrings.back();
685 if (last.substr(0, 4) ==
"??? "
686 && last.find(
" 0x0 + ") != string::npos)
687 outputStrings.pop_back();
689 last = outputStrings.back();
690 if (last.substr(0, 13) ==
"libdyld.dylib"
691 && last.find(
" start + ") != string::npos)
692 outputStrings.pop_back();
695 remove_if(outputStrings.begin(), outputStrings.end(),
696 [](
const string &s) {
697 return s.find(
"_dispatch_queue_override_invoke") != string::npos
698 || s.find(
"_dispatch_root_queue_drain") != string::npos
699 || s.find(
"_dispatch_worker_thread2") != string::npos
700 || s.find(
"_dispatch_lane_serial_drain") != string::npos
701 || s.find(
"_dispatch_lane_barrier_sync_invoke_and_complete") != string::npos
702 || s.find(
"_dispatch_lane_invoke") != string::npos
703 || s.find(
"_dispatch_workloop_worker_thread") != string::npos
704 || s.find(
"_dispatch_continuation_pop") != string::npos
705 || s.find(
"_dispatch_main_queue_callback_4CF") != string::npos
706 || s.find(
"__CFRunLoopDoObservers") != string::npos
707 || s.find(
"__CFRunLoopDoSource0") != string::npos
708 || s.find(
"__CFRunLoopDoSources0") != string::npos
709 || s.find(
"__CFRunLoopRun") != string::npos
710 || s.find(
"__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__") != string::npos
711 || s.find(
"__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__") != string::npos
712 || s.find(
"__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__") != string::npos
713 || s.find(
"_CFXRegistrationPost") != string::npos
714 || s.find(
"_CFXNotification") != string::npos
715 || s.find(
"_NSWindowSendWindowDidMove") != string::npos
716 || s.find(
"_NSSendEventToObservers") != string::npos
717 || s.find(
"NSCarbonMenuImpl") != string::npos
718 || s.find(
"NSSLMMenuEventHandler") != string::npos
719 || s.find(
"CopyCarbonUIElementAttributeValue") != string::npos
720 || s.find(
"NSApplication(NSEvent) _") != string::npos
721 || s.find(
"NSApplication(NSAppleEventHandling) _") != string::npos
722 || s.find(
"withWindowOrderingObserverHeuristic") != string::npos
723 || s.find(
"aeProcessAppleEvent") != string::npos
724 || s.find(
"dispatchEventAndSendReply") != string::npos
725 || s.find(
"aeDispatchAppleEvent") != string::npos
726 || s.find(
"_NSAppleEventManagerGenericHandler") != string::npos
727 || s.find(
"NSWindow _") != string::npos
728 || s.find(
"HIServices") != string::npos
729 || s.find(
"HIToolbox") != string::npos
730 || s.find(
"RunCurrentEventLoopInMode") != string::npos
731 || s.find(
"ReceiveNextEventCommon") != string::npos
732 || s.find(
"_BlockUntilNextEventMatchingListInModeWithFilter") != string::npos
733 || s.find(
"_DPSNextEvent") != string::npos
734 || s.find(
"_pthread_wqthread") != string::npos
735 || s.find(
"qt_plugin_instance") != string::npos
736 || s.find(
"QWindowSystemInterface::") != string::npos
737 || s.find(
"QWidgetPrivate::") != string::npos
738 || s.find(
"QApplicationPrivate::") != string::npos
739 || s.find(
"QGuiApplicationPrivate::") != string::npos
740 || s.find(
"QCoreApplication::notifyInternal2") != string::npos
741 || s.find(
"QCoreApplicationPrivate::") != string::npos;
743 outputStrings.end());
747 return outputStrings;