Skip to content

Commit dacd702

Browse files
rigor789edusperoni
authored andcommitted
feat(runtime): forward stdout and stderr to os_log for the CLI
Without a console an app's stdio is /dev/null, so print() and, on devices, NSLog never reach any log stream, and a CLI can't attach to them after launch. In debug builds whose CLI sets forwardStdio in the app's package.json, with stdout still /dev/null, the runtime now pipes them into os_log under the org.nativescript.stdio subsystem. Long lines are split like console messages.
1 parent 1519e69 commit dacd702

6 files changed

Lines changed: 131 additions & 7 deletions

File tree

‎NativeScript/NativeScript.mm‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include "runtime/NativeScriptException.h"
1212
#include "runtime/Runtime.h"
1313
#include "runtime/RuntimeConfig.h"
14+
#include "runtime/StdioForwarder.h"
1415
#include "runtime/Tasks.h"
1516

1617
using namespace v8;
@@ -242,6 +243,7 @@ - (instancetype)initializeWithConfig:(Config*)config {
242243
RuntimeConfig.LogToSystemConsole = [config LogToSystemConsole];
243244

244245
Runtime::Initialize();
246+
StartStdioForwarding();
245247
DestroyMainRuntime();
246248
runtime_ = new Runtime();
247249

‎NativeScript/runtime/Helpers.h‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -361,30 +361,32 @@ int LogFormat();
361361
// Unique per split message in the process, for the headers of format 1.
362362
uint32_t NextLogMessageId();
363363

364+
bool IsDevNull(int fd);
365+
364366
#if TNS_HAVE_OS_LOG
365367
// Logs the parts as one entry.
366-
static inline void TNS_WriteOsLogEntry(os_log_type_t type, std::string_view first,
368+
static inline void TNS_WriteOsLogEntry(os_log_t log, os_log_type_t type, std::string_view first,
367369
std::string_view second, std::string_view third = "") {
368-
os_log_with_type(OS_LOG_DEFAULT, type, "%{public}.*s%{public}.*s%{public}.*s",
370+
os_log_with_type(log, type, "%{public}.*s%{public}.*s%{public}.*s",
369371
static_cast<int>(first.size()), first.data(), static_cast<int>(second.size()),
370372
second.data(), static_cast<int>(third.size()), third.data());
371373
}
372374

373375
static inline void TNS_WriteToOsLog(const char* message, os_log_type_t type = OS_LOG_TYPE_DEFAULT,
374-
std::string_view prefix = "") {
376+
std::string_view prefix = "", os_log_t log = OS_LOG_DEFAULT) {
375377
std::string_view text(message);
376378
if (prefix.size() + text.size() <= kMaxLogChunkBytes) {
377-
TNS_WriteOsLogEntry(type, prefix, text);
379+
TNS_WriteOsLogEntry(log, type, prefix, text);
378380
} else if (LogFormat() >= 1) {
379381
ForEachFramedLogChunk(prefix, text, NextLogMessageId(),
380382
[&](std::string_view header, std::string_view piece) {
381-
TNS_WriteOsLogEntry(type, header, piece, kLogChunkTerminator);
383+
TNS_WriteOsLogEntry(log, type, header, piece, kLogChunkTerminator);
382384
});
383385
} else {
384386
// Repeated on every piece, so that each stays a complete log line.
385387
ForEachLogChunk(text, kMaxLogChunkBytes - prefix.size(),
386388
[&](std::string_view chunk, LogChunkBreak) {
387-
TNS_WriteOsLogEntry(type, prefix, chunk);
389+
TNS_WriteOsLogEntry(log, type, prefix, chunk);
388390
});
389391
}
390392
}

‎NativeScript/runtime/Helpers.mm‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,7 @@ void WriteDebugLine(tns::LogCategory category, const char* message) {
494494
}
495495
}
496496

497-
static bool IsDevNull(int fd) {
497+
bool tns::IsDevNull(int fd) {
498498
struct stat target;
499499
struct stat devNull;
500500
return fstat(fd, &target) == 0 && stat("/dev/null", &devNull) == 0 &&
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#ifndef StdioForwarder_h
2+
#define StdioForwarder_h
3+
4+
namespace tns {
5+
6+
// Sends what the app writes to stdout and stderr (print(), NSLog on devices) to
7+
// os_log. Without a console those go to /dev/null, and a process can't be
8+
// attached to later: its stdio is fixed at launch. Only debug builds whose CLI
9+
// asks for it through the forwardStdio key of the app's package.json do this.
10+
void StartStdioForwarding();
11+
12+
} // namespace tns
13+
14+
#endif /* StdioForwarder_h */
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#include "StdioForwarder.h"
2+
#include <Foundation/Foundation.h>
3+
#include <TargetConditionals.h>
4+
#include <dispatch/dispatch.h>
5+
#include <os/log.h>
6+
#include <stdio.h>
7+
#include <unistd.h>
8+
#include <memory>
9+
#include <mutex>
10+
#include <string>
11+
#include "Helpers.h"
12+
#include "Runtime.h"
13+
#include "RuntimeConfig.h"
14+
15+
namespace tns {
16+
17+
namespace {
18+
19+
// The CLI tells these entries apart from JS console output by this subsystem.
20+
constexpr const char* kStdioSubsystem = "org.nativescript.stdio";
21+
22+
// A longer line goes out in parts instead of growing the buffer without limit.
23+
constexpr size_t kMaxBufferedLineBytes = 64 * 1024;
24+
25+
void Forward(int fd, const char* category, dispatch_queue_t queue) {
26+
int fds[2];
27+
if (pipe(fds) != 0) {
28+
return;
29+
}
30+
if (dup2(fds[1], fd) < 0) {
31+
close(fds[0]);
32+
close(fds[1]);
33+
return;
34+
}
35+
close(fds[1]);
36+
37+
int readEnd = fds[0];
38+
os_log_t log = os_log_create(kStdioSubsystem, category);
39+
auto pending = std::make_shared<std::string>();
40+
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, readEnd, 0, queue);
41+
dispatch_source_set_event_handler(source, ^{
42+
char buffer[4096];
43+
ssize_t count = read(readEnd, buffer, sizeof(buffer));
44+
if (count <= 0) {
45+
return;
46+
}
47+
pending->append(buffer, count);
48+
49+
size_t start = 0;
50+
size_t end;
51+
while ((end = pending->find('\n', start)) != std::string::npos) {
52+
TNS_WriteToOsLog(pending->substr(start, end - start).c_str(), OS_LOG_TYPE_DEFAULT, "", log);
53+
start = end + 1;
54+
}
55+
pending->erase(0, start);
56+
57+
if (pending->size() >= kMaxBufferedLineBytes) {
58+
TNS_WriteToOsLog(pending->c_str(), OS_LOG_TYPE_DEFAULT, "", log);
59+
pending->clear();
60+
}
61+
});
62+
dispatch_resume(source);
63+
}
64+
65+
} // namespace
66+
67+
void StartStdioForwarding() {
68+
static std::once_flag once;
69+
std::call_once(once, [] {
70+
if (!RuntimeConfig.IsDebug || RuntimeConfig.ApplicationPath.empty()) {
71+
return;
72+
}
73+
74+
id value = Runtime::GetAppConfigValue("forwardStdio");
75+
if (value == nil || ![value boolValue] || !IsDevNull(STDOUT_FILENO)) {
76+
return;
77+
}
78+
79+
// Decided once and from stdout, which is about to stop being /dev/null.
80+
LogFormat();
81+
82+
// Otherwise stdout is fully buffered into a pipe, and print() only shows up
83+
// when the buffer fills.
84+
setvbuf(stdout, nullptr, _IOLBF, 0);
85+
86+
// Serial, so that the chunks of a split line stay together.
87+
dispatch_queue_t queue =
88+
dispatch_queue_create("org.nativescript.stdio", DISPATCH_QUEUE_SERIAL);
89+
Forward(STDOUT_FILENO, "stdout", queue);
90+
#if !TARGET_OS_SIMULATOR
91+
// On the simulator NSLog reaches the unified log as well, so forwarding
92+
// stderr there would print it twice.
93+
Forward(STDERR_FILENO, "stderr", queue);
94+
#endif
95+
});
96+
}
97+
98+
} // namespace tns

‎v8ios.xcodeproj/project.pbxproj‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,8 @@
340340
A1B2C3D40000000000000004 /* WorkerInspectorClient.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000002 /* WorkerInspectorClient.mm */; };
341341
F6191AB129C0FCE8003F588F /* InspectorServer.h in Headers */ = {isa = PBXBuildFile; fileRef = F6191AA929C0FCE7003F588F /* InspectorServer.h */; };
342342
F6191AB229C0FCE8003F588F /* InspectorServer.mm in Sources */ = {isa = PBXBuildFile; fileRef = F6191AAA29C0FCE7003F588F /* InspectorServer.mm */; settings = {COMPILER_FLAGS = "-fobjc-arc"; }; };
343+
A1C0DE5400000000000000A4 /* StdioForwarder.h in Headers */ = {isa = PBXBuildFile; fileRef = A1C0DE5200000000000000A2 /* StdioForwarder.h */; };
344+
A1C0DE5500000000000000A5 /* StdioForwarder.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1C0DE5300000000000000A3 /* StdioForwarder.mm */; };
343345
F6191AB629C0FF87003F588F /* utils.h in Headers */ = {isa = PBXBuildFile; fileRef = F6191AB429C0FF86003F588F /* utils.h */; };
344346
F6191AB729C0FF87003F588F /* utils.mm in Sources */ = {isa = PBXBuildFile; fileRef = F6191AB529C0FF86003F588F /* utils.mm */; };
345347
D3FA1E7A0000000000000004 /* NativeScriptDefaultMetadata.c in Sources */ = {isa = PBXBuildFile; fileRef = D3FA1E7A0000000000000002 /* NativeScriptDefaultMetadata.c */; };
@@ -819,6 +821,8 @@
819821
C2DDEB6B229EAC8200345BFE /* Console.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Console.cpp; sourceTree = "<group>"; };
820822
C2DDEB6D229EAC8200345BFE /* Helpers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Helpers.h; sourceTree = "<group>"; };
821823
A1C0DE5100000000000000A1 /* LogChunks.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = LogChunks.h; sourceTree = "<group>"; };
824+
A1C0DE5200000000000000A2 /* StdioForwarder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = StdioForwarder.h; sourceTree = "<group>"; };
825+
A1C0DE5300000000000000A3 /* StdioForwarder.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = StdioForwarder.mm; sourceTree = "<group>"; };
822826
C2DDEB6E229EAC8200345BFE /* Metadata.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Metadata.h; sourceTree = "<group>"; };
823827
C2DDEB6F229EAC8200345BFE /* ArrayAdapter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ArrayAdapter.h; sourceTree = "<group>"; };
824828
C2DDEB70229EAC8200345BFE /* Metadata.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = Metadata.mm; sourceTree = "<group>"; };
@@ -1499,6 +1503,8 @@
14991503
C266569C22B282BA00EE15CC /* FunctionReference.cpp */,
15001504
C2DDEB6D229EAC8200345BFE /* Helpers.h */,
15011505
A1C0DE5100000000000000A1 /* LogChunks.h */,
1506+
A1C0DE5200000000000000A2 /* StdioForwarder.h */,
1507+
A1C0DE5300000000000000A3 /* StdioForwarder.mm */,
15021508
C2DDEB7D229EAC8200345BFE /* Helpers.mm */,
15031509
AA5DBFD12EC191F8008D12F9 /* HttpLoader.h */,
15041510
AA5DBFD22EC191F8008D12F9 /* HttpLoader.mm */,
@@ -1669,6 +1675,7 @@
16691675
C2DDEB97229EAC8300345BFE /* Metadata.h in Headers */,
16701676
C247C16522F82842001D2CA2 /* v8-platform.h in Headers */,
16711677
F6191AB129C0FCE8003F588F /* InspectorServer.h in Headers */,
1678+
A1C0DE5400000000000000A4 /* StdioForwarder.h in Headers */,
16721679
C247C16722F82842001D2CA2 /* libplatform.h in Headers */,
16731680
C2DDEBA4229EAC8300345BFE /* Runtime.h in Headers */,
16741681
F1CB51842D5C37100042555E /* URLPatternImpl.h in Headers */,
@@ -2352,6 +2359,7 @@
23522359
C266569722AFFFB000EE15CC /* Reference.cpp in Sources */,
23532360
6573B9EE291FE5B700B0ED7C /* JSIRuntime.m in Sources */,
23542361
F6191AB229C0FCE8003F588F /* InspectorServer.mm in Sources */,
2362+
A1C0DE5500000000000000A5 /* StdioForwarder.mm in Sources */,
23552363
6573B9D3291FE29F00B0ED7C /* HostProxy.cpp in Sources */,
23562364
6573B9E5291FE2A700B0ED7C /* jsi.cpp in Sources */,
23572365
C2DDEBB3229EAC8300345BFE /* ClassBuilder.mm in Sources */,

0 commit comments

Comments
 (0)