Skip to content

Commit 7283f21

Browse files
authored
feat: stream structured logs from com.apple.os_trace_relay (#88)
Adds startDeviceLogStream([{ deviceId, processName }]), which reads com.apple.os_trace_relay and emits a deviceLogEntry event per os_log entry. Entries are selected by executable name so the stream follows an app across relaunches. When the stream cannot start or stops, an error is emitted so callers can fall back to the syslog relay.
1 parent ee896a2 commit 7283f21

5 files changed

Lines changed: 366 additions & 2 deletions

File tree

‎IOSDeviceLib/Constants.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ static const char *kInstallationProxy = "com.apple.mobile.installation_proxy";
4040
static const char *kHouseArrest = "com.apple.mobile.house_arrest";
4141
static const char *kNotificationProxy = "com.apple.mobile.notification_proxy";
4242
static const char *kSyslog = "com.apple.syslog_relay";
43+
static const char *kOsTraceRelay = "com.apple.os_trace_relay";
4344
static const char *kMobileImageMounter =
4445
"com.apple.mobile.mobile_image_mounter";
4546
static const char *kDebugServer = "com.apple.debugserver";

‎IOSDeviceLib/IOSDeviceLib.cpp‎

Lines changed: 250 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1302,6 +1302,240 @@ void device_log(std::string device_identifier, std::string method_id) {
13021302
delete[] buffer;
13031303
}
13041304

1305+
#ifndef _WIN32
1306+
// AMDServiceConnectionReceive may return fewer bytes than requested.
1307+
bool receive_exact(ServiceConnRef connection, char *buffer, size_t size) {
1308+
size_t received = 0;
1309+
while (received < size) {
1310+
int bytes_read = AMDServiceConnectionReceive(connection, buffer + received,
1311+
size - received);
1312+
if (bytes_read <= 0) {
1313+
return false;
1314+
}
1315+
received += bytes_read;
1316+
}
1317+
return true;
1318+
}
1319+
1320+
template <typename T> T read_le(const std::vector<char> &data, size_t offset) {
1321+
T value;
1322+
memcpy(&value, data.data() + offset, sizeof(T));
1323+
return value;
1324+
}
1325+
1326+
const char *os_trace_level_name(uint8_t level) {
1327+
switch (level) {
1328+
case 0x00:
1329+
return "notice";
1330+
case 0x01:
1331+
return "info";
1332+
case 0x02:
1333+
return "debug";
1334+
case 0x03:
1335+
return "userAction";
1336+
case 0x10:
1337+
return "error";
1338+
case 0x11:
1339+
return "fault";
1340+
default:
1341+
return "unknown";
1342+
}
1343+
}
1344+
1345+
// Record layout of com.apple.os_trace_relay activity stream entries, as
1346+
// documented by pymobiledevice3 (services/os_trace.py): a fixed header, then
1347+
// the NUL-terminated process path, then the sender image path, message,
1348+
// subsystem and category, sized by header fields that include their NUL.
1349+
const size_t kOsTraceHeaderSize = 129;
1350+
1351+
bool parse_os_trace_entry(const std::vector<char> &data, json &entry) {
1352+
if (data.size() < kOsTraceHeaderSize) {
1353+
return false;
1354+
}
1355+
1356+
uint32_t seconds = read_le<uint32_t>(data, 55);
1357+
uint32_t microseconds = read_le<uint32_t>(data, 63);
1358+
uint16_t image_size = read_le<uint16_t>(data, 107);
1359+
uint16_t message_size = read_le<uint16_t>(data, 109);
1360+
uint32_t subsystem_size = read_le<uint32_t>(data, 117);
1361+
uint32_t category_size = read_le<uint32_t>(data, 121);
1362+
1363+
size_t offset = kOsTraceHeaderSize;
1364+
auto process_end = std::find(data.begin() + offset, data.end(), '\0');
1365+
if (process_end == data.end()) {
1366+
return false;
1367+
}
1368+
std::string process(data.begin() + offset, process_end);
1369+
offset = process_end - data.begin() + 1;
1370+
1371+
auto take = [&](size_t size, std::string &out) {
1372+
if (size == 0) {
1373+
return true;
1374+
}
1375+
if (offset + size > data.size()) {
1376+
return false;
1377+
}
1378+
out.assign(data.data() + offset, size - 1);
1379+
offset += size;
1380+
return true;
1381+
};
1382+
1383+
std::string image, message, subsystem, category;
1384+
if (!take(image_size, image) || !take(message_size, message) ||
1385+
!take(subsystem_size, subsystem) || !take(category_size, category)) {
1386+
return false;
1387+
}
1388+
1389+
entry["pid"] = read_le<uint32_t>(data, 9);
1390+
entry["thread"] = read_le<uint64_t>(data, 83);
1391+
entry["timestamp"] = seconds * 1000.0 + microseconds / 1000.0;
1392+
entry["level"] = os_trace_level_name((uint8_t)data[68]);
1393+
entry["process"] = process;
1394+
entry["image"] = image;
1395+
entry["message"] = message;
1396+
if (!subsystem.empty()) {
1397+
entry["subsystem"] = subsystem;
1398+
}
1399+
if (!category.empty()) {
1400+
entry["category"] = category;
1401+
}
1402+
return true;
1403+
}
1404+
1405+
std::string path_basename(const std::string &path) {
1406+
size_t slash = path.find_last_of('/');
1407+
return slash == std::string::npos ? path : path.substr(slash + 1);
1408+
}
1409+
1410+
// Larger than any os_log record; a bigger size means the stream is out of step.
1411+
const uint32_t kMaxOsTraceRecordSize = 1 << 20;
1412+
1413+
// Prints the entries of an os_trace_relay activity stream until it stops, and
1414+
// returns why it stopped.
1415+
const char *stream_os_trace_entries(ServiceConnRef connection,
1416+
const std::string &device_identifier,
1417+
const std::string &process_name,
1418+
const std::string &method_id) {
1419+
int pid = -1;
1420+
int message_filter = 0xFFFF;
1421+
// Payload | historical | callstack | debug, as Console.app requests.
1422+
int stream_flags = 0x3C;
1423+
CFStringRef keys[] = {create_CFString("Request"), create_CFString("Pid"),
1424+
create_CFString("MessageFilter"),
1425+
create_CFString("StreamFlags")};
1426+
CFTypeRef values[] = {create_CFString("StartActivity"),
1427+
CFNumberCreate(NULL, kCFNumberIntType, &pid),
1428+
CFNumberCreate(NULL, kCFNumberIntType, &message_filter),
1429+
CFNumberCreate(NULL, kCFNumberIntType, &stream_flags)};
1430+
CFDictionaryRef request = CFDictionaryCreate(
1431+
NULL, (const void **)keys, (const void **)values, 4,
1432+
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1433+
long send_result = send_con_message(connection, request);
1434+
CFRelease(request);
1435+
for (int i = 0; i < 4; i++) {
1436+
CFRelease(keys[i]);
1437+
CFRelease(values[i]);
1438+
}
1439+
if (send_result) {
1440+
return "Could not start the os_trace_relay activity stream";
1441+
}
1442+
1443+
// The reply is a little-endian length of the length, the length itself,
1444+
// then a plist with the request status.
1445+
uint32_t length_size = 0;
1446+
std::vector<char> length_bytes;
1447+
std::vector<char> reply;
1448+
bool reply_ok = receive_exact(connection, (char *)&length_size, 4) &&
1449+
length_size > 0 && length_size <= 8;
1450+
uint64_t reply_size = 0;
1451+
if (reply_ok) {
1452+
length_bytes.resize(length_size);
1453+
reply_ok = receive_exact(connection, length_bytes.data(), length_size);
1454+
memcpy(&reply_size, length_bytes.data(), length_size);
1455+
}
1456+
if (reply_ok && reply_size > 0 && reply_size < (1 << 20)) {
1457+
reply.resize(reply_size);
1458+
reply_ok = receive_exact(connection, reply.data(), reply_size);
1459+
} else {
1460+
reply_ok = false;
1461+
}
1462+
1463+
std::map<std::string, boost::any> reply_dict;
1464+
if (reply_ok) {
1465+
Plist::readPlist(reply.data(), reply.size(), reply_dict);
1466+
}
1467+
const std::string *status =
1468+
reply_dict.count("Status")
1469+
? boost::any_cast<std::string>(&reply_dict["Status"])
1470+
: nullptr;
1471+
if (!status || *status != "RequestSuccessful") {
1472+
return "The device refused the os_trace_relay activity stream";
1473+
}
1474+
1475+
std::vector<char> record;
1476+
while (true) {
1477+
char marker = 0;
1478+
uint32_t record_size = 0;
1479+
if (!receive_exact(connection, &marker, 1) || marker != 0x02 ||
1480+
!receive_exact(connection, (char *)&record_size, 4) ||
1481+
record_size > kMaxOsTraceRecordSize) {
1482+
break;
1483+
}
1484+
record.resize(record_size);
1485+
if (!receive_exact(connection, record.data(), record_size)) {
1486+
break;
1487+
}
1488+
1489+
json entry;
1490+
if (!parse_os_trace_entry(record, entry)) {
1491+
continue;
1492+
}
1493+
if (!process_name.empty() &&
1494+
path_basename(entry["process"].get<std::string>()) != process_name) {
1495+
continue;
1496+
}
1497+
1498+
json message;
1499+
message[kDeviceId] = device_identifier;
1500+
message["entry"] = entry;
1501+
message[kId] = method_id;
1502+
print(message);
1503+
}
1504+
1505+
return "The os_trace_relay activity stream ended";
1506+
}
1507+
1508+
// Structured logs from com.apple.os_trace_relay. Only entries whose process
1509+
// executable is named process_name are printed (all of them when it is
1510+
// empty), matched by name so the stream follows the app across relaunches.
1511+
// The stream never ends normally, so its end is always reported as an error.
1512+
void device_log_stream(std::string device_identifier, std::string process_name,
1513+
std::string method_id) {
1514+
ServiceInfo serviceInfo = start_secure_service(
1515+
device_identifier, kOsTraceRelay, method_id, true, true);
1516+
if (!serviceInfo.socket) {
1517+
return;
1518+
}
1519+
1520+
// This runs on a detached thread, where an uncaught exception would
1521+
// terminate the whole process.
1522+
const char *reason;
1523+
try {
1524+
reason = stream_os_trace_entries(serviceInfo.connection, device_identifier,
1525+
process_name, method_id);
1526+
} catch (...) {
1527+
reason = "The os_trace_relay activity stream failed";
1528+
}
1529+
1530+
start_service_mutex.lock();
1531+
serviceConnections.erase(serviceInfo.connection_id);
1532+
start_service_mutex.unlock();
1533+
AMDServiceConnectionInvalidate(serviceInfo.connection);
1534+
1535+
print_error(reason, device_identifier, method_id, kAMDAPIInternalError);
1536+
}
1537+
#endif
1538+
13051539
void post_notification(std::string device_identifier,
13061540
PostNotificationInfo post_notification_info,
13071541
std::string method_id) {
@@ -1732,6 +1966,22 @@ int main() {
17321966
device_identifier_json.get<std::string>();
17331967
perform_detached_operation(device_log, device_identifier, method_id);
17341968
}
1969+
} else if (method_name == "logStream") {
1970+
for (json &arg : method_args) {
1971+
if (!validate_device_id_and_attrs(arg, method_id, {}))
1972+
continue;
1973+
1974+
std::string device_identifier = arg.value(kDeviceId, "");
1975+
#ifdef _WIN32
1976+
print_error("Structured device logs are not supported on Windows",
1977+
device_identifier, method_id, kAMDAPIInternalError);
1978+
#else
1979+
std::string process_name = arg.value("processName", "");
1980+
std::thread([=]() {
1981+
device_log_stream(device_identifier, process_name, method_id);
1982+
}).detach();
1983+
#endif
1984+
}
17351985
} else if (method_name == "postNotification") {
17361986
for (json &arg : method_args) {
17371987
if (!validate_device_id_and_attrs(arg, method_id,

‎ios-device-lib.js‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const MethodNames = {
1010
uninstall: "uninstall",
1111
list: "list",
1212
log: "log",
13+
logStream: "logStream",
1314
upload: "upload",
1415
download: "download",
1516
read: "read",
@@ -23,7 +24,8 @@ const MethodNames = {
2324
};
2425

2526
const Events = {
26-
deviceLogData: "deviceLogData"
27+
deviceLogData: "deviceLogData",
28+
deviceLogEntry: "deviceLogEntry"
2729
};
2830

2931
class IOSDeviceLib extends EventEmitter {
@@ -89,6 +91,18 @@ class IOSDeviceLib extends EventEmitter {
8991
this._getPromise(MethodNames.log, deviceIdentifiers, { shouldEmit: true, disregardTimeout: true, doNotFailOnDeviceLost: true });
9092
}
9193

94+
/**
95+
* Streams structured os_log entries (com.apple.os_trace_relay). Each entry is emitted
96+
* as a "deviceLogEntry" event. So is an error, when the stream cannot be started or
97+
* stops, after which nothing more is emitted for that device.
98+
*/
99+
startDeviceLogStream(logStreamArray) {
100+
// One request per device, so losing one device does not stop the others' streams.
101+
logStreamArray.forEach(logStream => {
102+
this._getPromise(MethodNames.logStream, [logStream], { shouldEmit: true, emitEventName: Events.deviceLogEntry, disregardTimeout: true, doNotFailOnDeviceLost: true, stopOnError: true });
103+
});
104+
}
105+
92106
connectToPort(connectToPortArray) {
93107
return connectToPortArray.map(connectToPortObject => this._getPromise(MethodNames.connectToPort, [connectToPortObject]));
94108
}
@@ -153,7 +167,10 @@ class IOSDeviceLib extends EventEmitter {
153167

154168
delete message.id;
155169
if (options && options.shouldEmit) {
156-
this.emit(Events.deviceLogData, message);
170+
if (options.stopOnError && message.error) {
171+
removeListeners();
172+
}
173+
this.emit(options.emitEventName || Events.deviceLogData, message);
157174
} else {
158175
handleMessage(message);
159176
}

‎test/ios-device-lib.js‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,5 +134,59 @@ describe("ios-device-lib", () => {
134134
assert.equal(handler.listenerCount(Constants.DeviceLostEventName), 0);
135135
assert.equal(handler.listenerCount(Constants.DataEventName), 0);
136136
});
137+
138+
it("emits structured log stream entries as deviceLogEntry, not deviceLogData", () => {
139+
const lib = createLib();
140+
const entries = [];
141+
const legacy = [];
142+
lib.on("deviceLogEntry", (data) => entries.push(data));
143+
lib.on("deviceLogData", (data) => legacy.push(data));
144+
145+
lib.startDeviceLogStream([{ deviceId: deviceA, processName: "app" }]);
146+
const request = lib._iosDeviceLibStdioHandler.written[0].methods[0];
147+
assert.equal(request.name, "logStream");
148+
assert.deepEqual(request.args, [{ deviceId: deviceA, processName: "app" }]);
149+
150+
const entry = { pid: 1, message: "CONSOLE LOG: hi" };
151+
lib._iosDeviceLibStdioHandler.emit(Constants.DataEventName, { id: lastMessageId(lib), deviceId: deviceA, entry });
152+
153+
assert.deepEqual(entries, [{ deviceId: deviceA, entry }]);
154+
assert.deepEqual(legacy, []);
155+
});
156+
157+
it("streams each device with its own request, so losing one device leaves the others streaming", () => {
158+
const lib = createLib();
159+
const entries = [];
160+
lib.on("deviceLogEntry", (data) => entries.push(data));
161+
162+
lib.startDeviceLogStream([{ deviceId: deviceA, processName: "app" }, { deviceId: deviceB, processName: "app" }]);
163+
const written = lib._iosDeviceLibStdioHandler.written;
164+
assert.equal(written.length, 2);
165+
const [idA, idB] = written.map((request) => request.methods[0].id);
166+
assert.deepEqual(written[1].methods[0].args, [{ deviceId: deviceB, processName: "app" }]);
167+
168+
emitDeviceLost(lib, deviceA);
169+
const entry = { pid: 1, message: "CONSOLE LOG: hi" };
170+
emitResponse(lib, idA, { deviceId: deviceA, entry });
171+
emitResponse(lib, idB, { deviceId: deviceB, entry });
172+
173+
assert.deepEqual(entries, [{ deviceId: deviceB, entry }]);
174+
});
175+
176+
it("emits a stream error once and then stops listening for that stream", () => {
177+
const lib = createLib();
178+
const entries = [];
179+
lib.on("deviceLogEntry", (data) => entries.push(data));
180+
181+
lib.startDeviceLogStream([{ deviceId: deviceA, processName: "app" }]);
182+
const id = lastMessageId(lib);
183+
const error = { message: "The os_trace_relay activity stream ended", code: 1, deviceId: deviceA };
184+
emitResponse(lib, id, { deviceId: deviceA, error });
185+
emitResponse(lib, id, { deviceId: deviceA, entry: { pid: 1, message: "late" } });
186+
187+
assert.deepEqual(entries, [{ deviceId: deviceA, error }]);
188+
assert.equal(lib._iosDeviceLibStdioHandler.listenerCount(Constants.DataEventName), 0);
189+
assert.equal(lib._iosDeviceLibStdioHandler.listenerCount(Constants.DeviceLostEventName), 0);
190+
});
137191
});
138192
});

0 commit comments

Comments
 (0)