diff --git a/NativeScript/NativeScript.mm b/NativeScript/NativeScript.mm index 0576ea72..a660a6b6 100644 --- a/NativeScript/NativeScript.mm +++ b/NativeScript/NativeScript.mm @@ -11,6 +11,7 @@ #include "runtime/NativeScriptException.h" #include "runtime/Runtime.h" #include "runtime/RuntimeConfig.h" +#include "runtime/StdioForwarder.h" #include "runtime/Tasks.h" #include "runtime/generated/Version.h" @@ -243,6 +244,7 @@ - (instancetype)initializeWithConfig:(Config*)config { RuntimeConfig.LogToSystemConsole = [config LogToSystemConsole]; Runtime::Initialize(); + StartStdioForwarding(); DestroyMainRuntime(); std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); runtime_ = new Runtime(); diff --git a/NativeScript/runtime/Helpers.h b/NativeScript/runtime/Helpers.h index 6f1aa77a..64ba155b 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -450,30 +450,31 @@ int LogFormat(); // Unique per split message in the process, for the headers of format 1. uint32_t NextLogMessageId(); +bool IsDevNull(int fd); + #if TNS_HAVE_OS_LOG // Logs the two parts as one entry. -static inline void TNS_WriteOsLogEntry(os_log_type_t type, std::string_view first, +static inline void TNS_WriteOsLogEntry(os_log_t log, os_log_type_t type, std::string_view first, std::string_view second) { - os_log_with_type(OS_LOG_DEFAULT, type, "%{public}.*s%{public}.*s", + os_log_with_type(log, type, "%{public}.*s%{public}.*s", static_cast(first.size()), first.data(), static_cast(second.size()), second.data()); } -static inline void TNS_WriteToOsLog(const char* message, os_log_type_t type = OS_LOG_TYPE_DEFAULT, - std::string_view prefix = "") { - std::string_view text(message); +static inline void TNS_WriteToOsLog(std::string_view text, os_log_type_t type = OS_LOG_TYPE_DEFAULT, + std::string_view prefix = "", os_log_t log = OS_LOG_DEFAULT) { if (prefix.size() + text.size() <= kMaxLogChunkBytes) { - TNS_WriteOsLogEntry(type, prefix, text); + TNS_WriteOsLogEntry(log, type, prefix, text); } else if (LogFormat() >= 1) { ForEachFramedLogChunk(prefix, text, NextLogMessageId(), [&](std::string_view header, std::string_view piece) { - TNS_WriteOsLogEntry(type, header, piece); + TNS_WriteOsLogEntry(log, type, header, piece); }); } else { // Repeated on every piece, so that each stays a complete log line. ForEachLogChunk(text, kMaxLogChunkBytes - prefix.size(), [&](std::string_view chunk, LogChunkBreak) { - TNS_WriteOsLogEntry(type, prefix, chunk); + TNS_WriteOsLogEntry(log, type, prefix, chunk); }); } } diff --git a/NativeScript/runtime/Helpers.mm b/NativeScript/runtime/Helpers.mm index 7ffad70c..0eca20b7 100644 --- a/NativeScript/runtime/Helpers.mm +++ b/NativeScript/runtime/Helpers.mm @@ -516,7 +516,7 @@ void WriteDebugLine(tns::LogCategory category, const char* message) { } } -static bool IsDevNull(int fd) { +bool tns::IsDevNull(int fd) { struct stat target; struct stat devNull; return fstat(fd, &target) == 0 && stat("/dev/null", &devNull) == 0 && diff --git a/NativeScript/runtime/StdioForwarder.h b/NativeScript/runtime/StdioForwarder.h new file mode 100644 index 00000000..dc32d847 --- /dev/null +++ b/NativeScript/runtime/StdioForwarder.h @@ -0,0 +1,14 @@ +#ifndef StdioForwarder_h +#define StdioForwarder_h + +namespace tns { + +// Sends what the app writes to stdout and stderr (print(), NSLog on devices) to +// os_log. Without a console those go to /dev/null, and a process can't be +// attached to later: its stdio is fixed at launch. Only debug builds whose CLI +// asks for it through the forwardStdio key of the app's package.json do this. +void StartStdioForwarding(); + +} // namespace tns + +#endif /* StdioForwarder_h */ diff --git a/NativeScript/runtime/StdioForwarder.mm b/NativeScript/runtime/StdioForwarder.mm new file mode 100644 index 00000000..55125969 --- /dev/null +++ b/NativeScript/runtime/StdioForwarder.mm @@ -0,0 +1,139 @@ +#include "StdioForwarder.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Helpers.h" +#include "Runtime.h" +#include "RuntimeConfig.h" + +namespace tns { + +namespace { + +// The CLI tells these entries apart from JS console output by this subsystem. +constexpr const char* kStdioSubsystem = "org.nativescript.stdio"; + +// A longer line goes out in parts instead of growing the buffer without limit. +constexpr size_t kMaxBufferedLineBytes = 64 * 1024; + +// Where to cut a full buffer so that the cut doesn't split a UTF-8 character: +// before the last character, whose bytes may not all have arrived yet. +size_t Utf8SafeCut(std::string_view text) { + size_t cut = text.size() - 1; + while (cut > 0 && text.size() - cut < 4 && + (static_cast(text[cut]) & 0xC0) == 0x80) { + cut--; + } + return cut; +} + +void Forward(int fd, const char* category, dispatch_queue_t queue) { + int fds[2]; + if (pipe(fds) != 0) { + return; + } + if (dup2(fds[1], fd) < 0) { + close(fds[0]); + close(fds[1]); + return; + } + close(fds[1]); + + int readEnd = fds[0]; + os_log_t log = os_log_create(kStdioSubsystem, category); + auto pending = std::make_shared(); + dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, readEnd, 0, queue); + // The handler's reference to the source keeps the source alive, with or + // without ARC, until it is cancelled. + dispatch_source_set_event_handler(source, ^{ + char buffer[4096]; + ssize_t count = read(readEnd, buffer, sizeof(buffer)); + if (count < 0 && (errno == EINTR || errno == EAGAIN)) { + return; + } + if (count <= 0) { + // The app replaced or closed the descriptor, so nothing can write to the + // pipe again, and the source would otherwise fire without end. + if (!pending->empty()) { + TNS_WriteToOsLog(*pending, OS_LOG_TYPE_DEFAULT, "", log); + pending->clear(); + } + dispatch_source_cancel(source); + return; + } + // os_log ends a string at a NUL byte, so a NUL would hide the rest of the + // line. + for (ssize_t i = 0; i < count; i++) { + if (buffer[i] != '\0') { + pending->push_back(buffer[i]); + } + } + + std::string_view text(*pending); + size_t start = 0; + size_t end; + while ((end = text.find('\n', start)) != std::string_view::npos) { + TNS_WriteToOsLog(text.substr(start, end - start), OS_LOG_TYPE_DEFAULT, "", log); + start = end + 1; + } + pending->erase(0, start); + + if (pending->size() >= kMaxBufferedLineBytes) { + size_t cut = Utf8SafeCut(*pending); + TNS_WriteToOsLog(std::string_view(*pending).substr(0, cut), OS_LOG_TYPE_DEFAULT, "", log); + pending->erase(0, cut); + } + }); + dispatch_source_set_cancel_handler(source, ^{ + close(readEnd); + }); + dispatch_resume(source); +} + +} // namespace + +void StartStdioForwarding() { + static std::once_flag once; + std::call_once(once, [] { + if (!RuntimeConfig.IsDebug || RuntimeConfig.ApplicationPath.empty()) { + return; + } + + id value = Runtime::GetAppConfigValue("forwardStdio"); + if (value != (__bridge id)kCFBooleanTrue || !IsDevNull(STDOUT_FILENO)) { + return; + } + + // Decided once and from stdout, which is about to stop being /dev/null. + LogFormat(); + + // Otherwise stdout is fully buffered into a pipe, and print() only shows up + // when the buffer fills. + setvbuf(stdout, nullptr, _IOLBF, 0); + + // Serial, so that the chunks of a split line stay together. + dispatch_queue_t queue = + dispatch_queue_create("org.nativescript.stdio", DISPATCH_QUEUE_SERIAL); + Forward(STDOUT_FILENO, "stdout", queue); +#if !TARGET_OS_SIMULATOR && !TARGET_OS_MACCATALYST + // On the simulator and Mac Catalyst NSLog reaches the unified log as well, + // so forwarding stderr there would print it twice. With + // OS_ACTIVITY_DT_MODE set, os_log copies every entry to stderr, so + // forwarding it would feed the forwarder's own output back into the pipe. + if (IsDevNull(STDERR_FILENO) && getenv("OS_ACTIVITY_DT_MODE") == nullptr) { + Forward(STDERR_FILENO, "stderr", queue); + } +#endif + }); +} + +} // namespace tns diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 95a518f0..f3160c3c 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -354,6 +354,8 @@ A1B2C3D4000000000000000C /* InspectorQueue.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000000000000A /* InspectorQueue.mm */; }; F6191AB129C0FCE8003F588F /* InspectorServer.h in Headers */ = {isa = PBXBuildFile; fileRef = F6191AA929C0FCE7003F588F /* InspectorServer.h */; }; F6191AB229C0FCE8003F588F /* InspectorServer.mm in Sources */ = {isa = PBXBuildFile; fileRef = F6191AAA29C0FCE7003F588F /* InspectorServer.mm */; settings = {COMPILER_FLAGS = "-fobjc-arc"; }; }; + A1C0DE5400000000000000A4 /* StdioForwarder.h in Headers */ = {isa = PBXBuildFile; fileRef = A1C0DE5200000000000000A2 /* StdioForwarder.h */; }; + A1C0DE5500000000000000A5 /* StdioForwarder.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1C0DE5300000000000000A3 /* StdioForwarder.mm */; }; F6191AB629C0FF87003F588F /* utils.h in Headers */ = {isa = PBXBuildFile; fileRef = F6191AB429C0FF86003F588F /* utils.h */; }; F6191AB729C0FF87003F588F /* utils.mm in Sources */ = {isa = PBXBuildFile; fileRef = F6191AB529C0FF86003F588F /* utils.mm */; }; D3FA1E7A0000000000000004 /* NativeScriptDefaultMetadata.c in Sources */ = {isa = PBXBuildFile; fileRef = D3FA1E7A0000000000000002 /* NativeScriptDefaultMetadata.c */; }; @@ -849,6 +851,8 @@ C2DDEB6B229EAC8200345BFE /* Console.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Console.cpp; sourceTree = ""; }; C2DDEB6D229EAC8200345BFE /* Helpers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Helpers.h; sourceTree = ""; }; A1C0DE5100000000000000A1 /* LogChunks.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = LogChunks.h; sourceTree = ""; }; + A1C0DE5200000000000000A2 /* StdioForwarder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = StdioForwarder.h; sourceTree = ""; }; + A1C0DE5300000000000000A3 /* StdioForwarder.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = StdioForwarder.mm; sourceTree = ""; }; C2DDEB6E229EAC8200345BFE /* Metadata.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Metadata.h; sourceTree = ""; }; C2DDEB6F229EAC8200345BFE /* ArrayAdapter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ArrayAdapter.h; sourceTree = ""; }; C2DDEB70229EAC8200345BFE /* Metadata.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = Metadata.mm; sourceTree = ""; }; @@ -1557,6 +1561,8 @@ C266569C22B282BA00EE15CC /* FunctionReference.cpp */, C2DDEB6D229EAC8200345BFE /* Helpers.h */, A1C0DE5100000000000000A1 /* LogChunks.h */, + A1C0DE5200000000000000A2 /* StdioForwarder.h */, + A1C0DE5300000000000000A3 /* StdioForwarder.mm */, C2DDEB7D229EAC8200345BFE /* Helpers.mm */, AA5DBFD12EC191F8008D12F9 /* HttpLoader.h */, AA5DBFD22EC191F8008D12F9 /* HttpLoader.mm */, @@ -1752,6 +1758,7 @@ C2DDEB97229EAC8300345BFE /* Metadata.h in Headers */, C247C16522F82842001D2CA2 /* v8-platform.h in Headers */, F6191AB129C0FCE8003F588F /* InspectorServer.h in Headers */, + A1C0DE5400000000000000A4 /* StdioForwarder.h in Headers */, C247C16722F82842001D2CA2 /* libplatform.h in Headers */, C2DDEBA4229EAC8300345BFE /* Runtime.h in Headers */, F1CB51842D5C37100042555E /* URLPatternImpl.h in Headers */, @@ -2542,6 +2549,7 @@ C266569722AFFFB000EE15CC /* Reference.cpp in Sources */, 6573B9EE291FE5B700B0ED7C /* JSIRuntime.m in Sources */, F6191AB229C0FCE8003F588F /* InspectorServer.mm in Sources */, + A1C0DE5500000000000000A5 /* StdioForwarder.mm in Sources */, 6573B9D3291FE29F00B0ED7C /* HostProxy.cpp in Sources */, 6573B9E5291FE2A700B0ED7C /* jsi.cpp in Sources */, C2DDEBB3229EAC8300345BFE /* ClassBuilder.mm in Sources */,