/
LoggerClient.m
3197 lines (2865 loc) · 106 KB
/
LoggerClient.m
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* LoggerClient.m
*
* version 1.9.7 09-JAN-2019
*
* Main implementation of the NSLogger client side code
* Part of NSLogger (client side)
* https://github.com/fpillet/NSLogger
*
* BSD license follows (http://www.opensource.org/licenses/bsd-license.php)
*
* Copyright (c) 2010-2018 Florent Pillet All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions in
* binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution. Neither the name of Florent
* Pillet nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#import <sys/time.h>
#import <arpa/inet.h>
#import <stdlib.h>
#import "LoggerClient.h"
#import "LoggerCommon.h"
#import <sys/types.h>
#import <sys/sysctl.h>
#import <sys/utsname.h>
#import <dlfcn.h>
#import <fcntl.h>
#import <stdatomic.h>
#if TARGET_OS_IPHONE
#import <UIKit/UIDevice.h>
#endif
/* --------------------------------------------------------------------------------
* IMPLEMENTATION NOTES:
*
* The logger runs in a separate thread. You can start
* logging very early (as soon as your code starts running), logs will be
* buffered and sent to the log viewer as soon as a connection is acquired.
* This makes the logger suitable for use in conditions where you usually
* don't have a connection to a remote machine yet (early wakeup, network
* down, etc).
*
* When you call one of the public logging functions, the logger is designed
* to return to your application as fast as possible. It enqueues logs to
* send for processing by its own thread, while your application keeps running.
*
* The logger does buffer logs while not connected to a desktop
* logger. It uses Bonjour to find a logger on the local network, and can
* optionally connect to a remote logger identified by an IP address / port
* or a Host Name / port.
*
* The logger can optionally output its logs to the console, like NSLog().
*
* The logger can optionally buffer its logs to a file for which you specify the
* full path. Upon connection to the desktop viewer, the file contents are
* transmitted to the viewer prior to sending new logs. When the whole file
* content has been transmitted, it is emptied.
*
* Multiple loggers can coexist at the same time. You can perfectly use a
* logger for your debug traces, and another that connects remotely to help
* diagnose issues while the application runs on your user's device.
*
* The logger can optionally capture stdout and stderr. When running an
* application from the IDE, this will automatically capture everything that
* goes into the debugger console log, and insert it in the stream of logs
* sent to the viewer.
*
* Using the logger's flexible packet format, you can customize logging by
* creating your own log types, and customize the desktop viewer to display
* runtime information panels for your application.
* --------------------------------------------------------------------------------
*/
/* Logger internal debug flags */
// Set to 0 to disable internal debug completely
// Set to 1 to activate console logs when running the logger itself
// Set to 2 to see every logging call issued by the app, too
#define LOGGER_DEBUG 0
#ifdef NSLog
#undef NSLog
#endif
// Internal debugging stuff for the logger itself
#if LOGGER_DEBUG
#define LOGGERDBG LoggerDbg
#if LOGGER_DEBUG > 1
#define LOGGERDBG2 LoggerDbg
#else
#define LOGGERDBG2(format, ...) do{}while(0)
#endif
// Internal logging function prototype
static void LoggerDbg(CFStringRef format, ...);
#else
#define LOGGERDBG(format, ...) do{}while(0)
#define LOGGERDBG2(format, ...) do{}while(0)
#endif
#if defined(__has_feature) && __has_feature(objc_arc)
#error LoggerClient.m must be compiled without Objective-C Automatic Reference Counting (CLANG_ENABLE_OBJC_ARC=NO)
#endif
struct Logger
{
CFStringRef bufferFile; // If non-NULL, all buffering is done to the specified file instead of in-memory
CFStringRef host; // Viewer host to connect to (instead of using Bonjour)
UInt32 port; // port on the viewer host
CFMutableArrayRef bonjourServiceBrowsers; // Active service browsers
CFMutableArrayRef bonjourServices; // Services being tried
NSNetServiceBrowser *bonjourDomainBrowser; // Domain browser
CFMutableArrayRef logQueue; // Message queue
pthread_mutex_t logQueueMutex; // A mutex we use to protect access to the log queue and some critical variables
pthread_cond_t logQueueEmpty;
dispatch_once_t workerThreadInit; // Use this to ensure creation of the worker thread is ever done only once for a given logger
pthread_t workerThread; // The worker thread responsible for Bonjour resolution, connection and logs transmission
CFRunLoopSourceRef messagePushedSource; // A message source that fires on the worker thread when messages are available for send
CFRunLoopSourceRef bufferFileChangedSource; // A message source that fires on the worker thread when the buffer file configuration changes
CFRunLoopSourceRef remoteOptionsChangedSource; // A message source that fires when option changes imply a networking strategy change (switch to/from Bonjour, direct host or file streaming)
CFWriteStreamRef logStream; // The connected stream we're writing to
CFWriteStreamRef bufferWriteStream; // If bufferFile not NULL and we're not connected, points to a stream for writing log data
CFReadStreamRef bufferReadStream; // If bufferFile not NULL, points to a read stream that will be emptied prior to sending the rest of in-memory messages
SCNetworkReachabilityRef reachability; // The reachability object we use to determine when the target host becomes reachable
SCNetworkReachabilityFlags reachabilityFlags; // Last known reachability flags - we use these to detect network transitions without network loss
CFRunLoopTimerRef reconnectTimer; // A timer to regularly check connection to the defined host, along with reachability for added reliability
uint8_t *sendBuffer; // data waiting to be sent
NSUInteger sendBufferSize;
NSUInteger sendBufferUsed; // number of bytes of the send buffer currently in use
NSUInteger sendBufferOffset; // offset in sendBuffer to start sending at
_Atomic(int32_t) messageSeq; // sequential message number (added to each message sent)
// settings
uint32_t options; // Flags, see enum above
CFStringRef bonjourServiceType; // leave NULL to use the default
CFStringRef bonjourServiceName; // leave NULL to use the first one available
// internal state
BOOL targetReachable; // Set to YES when the Reachability target (host or internet) is deemed reachable
BOOL connected; // Set to YES once the write stream declares the connection open
volatile BOOL quit; // Set to YES to terminate the logger worker thread's runloop
BOOL incompleteSendOfFirstItem; // set to YES if we are sending the first item in the queue and it's bigger than what the buffer can hold
};
/* Local prototypes */
static void LoggerFlushAllOnExit(void);
static void* LoggerWorkerThread(Logger *logger);
static void LoggerWriteMoreData(Logger *logger);
static void LoggerPushMessageToQueue(Logger *logger, CFDataRef message);
// Bonjour management
static void LoggerStartBonjourBrowsing(Logger *logger);
static void LoggerStopBonjourBrowsing(Logger *logger);
static void LoggerBrowseBonjourForServices(Logger *logger, CFStringRef domainName);
static void LoggerConnectToService(Logger *logger, NSNetService *service);
static void LoggerDisconnectFromService(Logger *logger, NSNetService *service);
@interface FPLLoggerBonjourDelegate : NSObject <NSNetServiceBrowserDelegate>
{
Logger *_logger;
}
- (instancetype)initWithLogger:(Logger *)logger;
@end
// Reachability and reconnect timer
static void LoggerRemoteSettingsChanged(Logger *logger);
static void LoggerStartReachabilityChecking(Logger *logger);
static void LoggerStopReachabilityChecking(Logger *logger);
static void LoggerReachabilityCallBack(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info);
static void LoggerStartReconnectTimer(Logger *logger);
static void LoggerStopReconnectTimer(Logger *logger);
static void LoggerTimedReconnectCallback(CFRunLoopTimerRef timer, void *info);
// Connection & stream management
static void LoggerTryConnect(Logger *logger);
static void LoggerWriteStreamTerminated(Logger *logger);
static void LoggerWriteStreamCallback(CFWriteStreamRef ws, CFStreamEventType event, void* info);
// File buffering
static void LoggerCreateBufferWriteStream(Logger *logger);
static void LoggerCreateBufferReadStream(Logger *logger);
static void LoggerEmptyBufferFile(Logger *logger);
static void LoggerFileBufferingOptionsChanged(Logger *logger);
static void LoggerFlushQueueToBufferStream(Logger *logger, BOOL firstEntryIsClientInfo);
// Encoding functions
static void LoggerPushClientInfoToFrontOfQueue(Logger *logger);
static void LoggerMessageAddTimestampAndThreadID(CFMutableDataRef encoder);
static CFMutableDataRef LoggerMessageCreate(int32_t seq);
static void LoggerMessageAddInt32(CFMutableDataRef encoder, int32_t anInt, int key);
#if __LP64__
static void LoggerMessageAddInt64(CFMutableDataRef data, int64_t anInt, int key);
#endif
static void LoggerMessageAddString(CFMutableDataRef encoder, CFStringRef aString, int key);
static void LoggerMessageAddData(CFMutableDataRef encoder, CFDataRef theData, int key, int partType);
static uint32_t LoggerMessageGetSeq(CFDataRef message);
/* Static objects */
static CFMutableArrayRef sLoggersList;
static Logger* volatile sDefaultLogger = NULL;
static Boolean sAtexitFunctionSet = FALSE;
static pthread_mutex_t sLoggersListMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t sDefaultLoggerMutex = PTHREAD_MUTEX_INITIALIZER;
// Console logging
static void LoggerStartGrabbingConsole(Logger *logger);
static void LoggerStopGrabbingConsole(Logger *logger);
static Logger ** consoleGrabbersList = NULL;
static unsigned consoleGrabbersListLength = 0;
static unsigned numActiveConsoleGrabbers = 0;
static pthread_mutex_t consoleGrabbersMutex = PTHREAD_MUTEX_INITIALIZER;
static int sConsolePipes[4] = { -1, -1, -1, -1 };
static int sSTDOUT = -1, sSTDERR = -1;
static int sSTDOUThadSIGPIPE, sSTDERRhadSIGPIPE;
static pthread_t consoleGrabThread;
// -----------------------------------------------------------------------------
#pragma mark -
#pragma mark Default logger
// -----------------------------------------------------------------------------
void LoggerSetDefaultLogger(Logger *defaultLogger)
{
pthread_mutex_lock(&sDefaultLoggerMutex);
sDefaultLogger = defaultLogger;
pthread_mutex_unlock(&sDefaultLoggerMutex);
}
Logger *LoggerGetDefaultLogger(void)
{
Logger *l = sDefaultLogger;
if (l == NULL)
{
pthread_mutex_lock(&sDefaultLoggerMutex);
l = sDefaultLogger;
if (l == NULL)
l = LoggerInit();
pthread_mutex_unlock(&sDefaultLoggerMutex);
}
return l;
}
Logger *LoggerCheckDefaultLogger(void)
{
return sDefaultLogger;
}
// -----------------------------------------------------------------------------
#pragma mark -
#pragma mark Initialization and setup
// -----------------------------------------------------------------------------
Logger *LoggerInit(void)
{
LOGGERDBG(CFSTR("LoggerInit defaultLogger=%p"), sDefaultLogger);
Logger *logger = (Logger *)malloc(sizeof(Logger));
bzero(logger, sizeof(Logger));
logger->logQueue = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
pthread_mutex_init(&logger->logQueueMutex, NULL);
pthread_cond_init(&logger->logQueueEmpty, NULL);
logger->bonjourServiceBrowsers = CFArrayCreateMutable(NULL, 4, &kCFTypeArrayCallBacks);
logger->bonjourServices = CFArrayCreateMutable(NULL, 4, &kCFTypeArrayCallBacks);
// for now we don't grow the send buffer, just use one page of memory which should be enouh
// (bigger messages will be sent separately)
logger->sendBuffer = (uint8_t *)malloc(4096);
logger->sendBufferSize = 4096;
logger->options = LOGGER_DEFAULT_OPTIONS;
#if LOGGER_DEBUG
// when debugging NSLogger itself, don't hijack the system console
// as we are sending messages to it for display
logger->options &= ~kLoggerOption_CaptureSystemConsole;
#endif
logger->quit = NO;
// Add logger to the list of existing loggers
// Set this logger as the default logger is none exist already
pthread_mutex_lock(&sLoggersListMutex);
if (sLoggersList == NULL)
{
CFArrayCallBacks callbacks;
bzero(&callbacks, sizeof(callbacks));
sLoggersList = CFArrayCreateMutable(NULL, 0, &callbacks);
}
CFArrayAppendValue(sLoggersList, (const void *)logger);
if (sDefaultLogger == NULL)
sDefaultLogger = logger;
// Configure a low level exit() callback that will flush all connected loggers
if (!sAtexitFunctionSet)
{
atexit(&LoggerFlushAllOnExit);
sAtexitFunctionSet = TRUE;
}
pthread_mutex_unlock(&sLoggersListMutex);
return logger;
}
void LoggerSetOptions(Logger *logger, uint32_t options)
{
LOGGERDBG(CFSTR("LoggerSetOptions options=0x%08lx"), options);
// If we choose to log to system console
// make sure we are not configured to capture the system console
// When debugging NSLogger itself, we never capture the system console either
if (options & kLoggerOption_LogToConsole)
options &= (uint32_t)~kLoggerOption_CaptureSystemConsole;
if (logger == NULL)
logger = LoggerGetDefaultLogger();
if (logger != NULL)
logger->options = options;
}
uint32_t LoggerGetOptions(Logger *logger)
{
logger = logger ?: LoggerGetDefaultLogger();
return logger ? logger->options : 0;
}
void LoggerSetupBonjour(Logger *logger, CFStringRef bonjourServiceType, CFStringRef bonjourServiceName)
{
LOGGERDBG(CFSTR("LoggerSetupBonjour serviceType=%@ serviceName=%@"), bonjourServiceType, bonjourServiceName);
if (logger == NULL)
logger = LoggerGetDefaultLogger();
if (logger != NULL)
{
pthread_mutex_lock(&logger->logQueueMutex);
BOOL change = ((bonjourServiceName != NULL) != (logger->bonjourServiceName != NULL) ||
(bonjourServiceName != NULL && CFStringCompare(bonjourServiceName, logger->bonjourServiceName, 0) != kCFCompareEqualTo))
|| ((bonjourServiceType != NULL) != (logger->bonjourServiceType != NULL) ||
(bonjourServiceType != NULL && CFStringCompare(bonjourServiceType, logger->bonjourServiceType, 0) != kCFCompareEqualTo));
if (bonjourServiceType != NULL)
CFRetain(bonjourServiceType);
if (bonjourServiceName != NULL)
CFRetain(bonjourServiceName);
if (logger->bonjourServiceType != NULL)
CFRelease(logger->bonjourServiceType);
if (logger->bonjourServiceName != NULL)
CFRelease(logger->bonjourServiceName);
logger->bonjourServiceType = bonjourServiceType;
logger->bonjourServiceName = bonjourServiceName;
if (change && logger->remoteOptionsChangedSource != NULL)
CFRunLoopSourceSignal(logger->remoteOptionsChangedSource);
pthread_mutex_unlock(&logger->logQueueMutex);
}
}
CFStringRef LoggerGetBonjourServiceType(Logger *logger)
{
logger = logger ?: LoggerGetDefaultLogger();
pthread_mutex_lock(&logger->logQueueMutex);
CFStringRef result = logger ? logger->bonjourServiceType : NULL;
pthread_mutex_unlock(&logger->logQueueMutex);
return result;
}
CFStringRef LoggerGetBonjourServiceName(Logger *logger)
{
logger = logger ?: LoggerGetDefaultLogger();
pthread_mutex_lock(&logger->logQueueMutex);
CFStringRef result = logger ? logger->bonjourServiceName : NULL;
pthread_mutex_unlock(&logger->logQueueMutex);
return result;
}
/// Stringification, see this:
/// http://gcc.gnu.org/onlinedocs/cpp/Stringification.html
#define nslogger_xstr(s) nslogger_str(s)
#define nslogger_str(s) #s
void LoggerSetupBonjourForBuildUser()
{
LoggerSetupBonjour(LoggerGetDefaultLogger(), NULL, CFSTR(nslogger_xstr(NSLOGGER_BUILD_USERNAME)));
}
void LoggerSetViewerHost(Logger *logger, CFStringRef hostName, UInt32 port)
{
logger = logger ?: LoggerGetDefaultLogger();
pthread_mutex_lock(&logger->logQueueMutex);
CFStringRef previousHost = logger->host;
UInt32 previousPort = logger->port;
logger->host = NULL;
if (hostName != NULL)
{
logger->host = CFStringCreateCopy(NULL, hostName);
logger->port = port;
}
if (logger->remoteOptionsChangedSource != NULL &&
(logger->port != previousPort ||
((hostName == NULL) != (previousHost == NULL)) ||
(hostName != NULL && CFStringCompare(hostName, previousHost, kCFCompareCaseInsensitive) != kCFCompareEqualTo)))
CFRunLoopSourceSignal(logger->remoteOptionsChangedSource);
if (previousHost != NULL)
CFRelease(previousHost);
pthread_mutex_unlock(&logger->logQueueMutex);
}
CFStringRef LoggerGetViewerHostName(Logger *logger)
{
logger = logger ?: LoggerGetDefaultLogger();
pthread_mutex_lock(&logger->logQueueMutex);
CFStringRef result = logger ? logger->host : NULL;
pthread_mutex_unlock(&logger->logQueueMutex);
return result;
}
UInt32 LoggerGetViewerPort(Logger *logger)
{
logger = logger ?: LoggerGetDefaultLogger();
pthread_mutex_lock(&logger->logQueueMutex);
UInt32 result = logger ? logger->port : 0;
pthread_mutex_unlock(&logger->logQueueMutex);
return result;
}
void LoggerSetBufferFile(Logger *logger, CFStringRef absolutePath)
{
logger = logger ?: LoggerGetDefaultLogger();
pthread_mutex_lock(&logger->logQueueMutex);
BOOL change = ((logger->bufferFile != NULL && absolutePath == NULL) ||
(logger->bufferFile == NULL && absolutePath != NULL) ||
(logger->bufferFile != NULL && absolutePath != NULL && CFStringCompare(logger->bufferFile, absolutePath, (CFStringCompareFlags) 0) != kCFCompareEqualTo));
if (change)
{
if (logger->bufferFile != NULL)
{
CFRelease(logger->bufferFile);
logger->bufferFile = NULL;
}
if (absolutePath != NULL)
logger->bufferFile = CFStringCreateCopy(NULL, absolutePath);
if (logger->bufferFileChangedSource != NULL)
CFRunLoopSourceSignal(logger->bufferFileChangedSource);
}
pthread_mutex_unlock(&logger->logQueueMutex);
}
CFStringRef LoggerGetBufferFile(Logger *logger)
{
logger = logger ?: LoggerGetDefaultLogger();
pthread_mutex_lock(&logger->logQueueMutex);
CFStringRef result = logger ? logger->bufferFile : NULL;
pthread_mutex_unlock(&logger->logQueueMutex);
return result;
}
Logger *LoggerStart(Logger *logger)
{
// will do nothing if logger is already started
if (logger == NULL)
logger = LoggerGetDefaultLogger();
if (logger != NULL)
{
if (logger->workerThread == NULL)
{
dispatch_once(&logger->workerThreadInit, ^{
// Start the work thread which performs the Bonjour search,
// connects to the logging service and forwards the logs
LOGGERDBG(CFSTR("LoggerStart logger=%p"), logger);
pthread_create(&logger->workerThread, NULL, (void *(*)(void *))&LoggerWorkerThread, logger);
// Grab console output if required
if (logger->options & kLoggerOption_CaptureSystemConsole)
LoggerStartGrabbingConsole(logger);
});
}
}
else
{
LOGGERDBG2(CFSTR("-> could not create logger"));
}
return logger;
}
void LoggerStop(Logger *logger)
{
LOGGERDBG(CFSTR("LoggerStop"));
pthread_mutex_lock(&sLoggersListMutex);
if (logger == NULL || logger == sDefaultLogger)
{
logger = sDefaultLogger;
sDefaultLogger = NULL;
}
if (sLoggersList != NULL && logger != NULL)
{
CFIndex where = CFArrayGetFirstIndexOfValue(sLoggersList, CFRangeMake(0, CFArrayGetCount(sLoggersList)), (void const *) logger);
if (where != -1)
CFArrayRemoveValueAtIndex(sLoggersList, where);
}
pthread_mutex_unlock(&sLoggersListMutex);
if (logger != NULL)
{
if (logger->workerThread != NULL)
{
LoggerStopGrabbingConsole(logger);
logger->quit = YES;
pthread_join(logger->workerThread, NULL);
logger->workerThread = NULL;
}
CFRelease(logger->bonjourServiceBrowsers);
CFRelease(logger->bonjourServices);
free(logger->sendBuffer);
if (logger->host != NULL)
CFRelease(logger->host);
if (logger->bufferFile != NULL)
CFRelease(logger->bufferFile);
if (logger->bonjourServiceType != NULL)
CFRelease(logger->bonjourServiceType);
if (logger->bonjourServiceName != NULL)
CFRelease(logger->bonjourServiceName);
// to make sure potential errors are caught, set the whole structure
// to a value that will make code crash if it tries using pointers to it.
memset(logger, 0x55, sizeof(Logger));
free(logger);
}
}
static void LoggerFlushAllOnExit()
{
// this function is automatically configured by NSLogger to flush all connected loggers
// on exit. this guarantees that the developer sees the last messages issued by the application.
// it is configured the first time a logger is initialized, so at the time we're being called
// the loggers list is never NULL
pthread_mutex_lock(&sLoggersListMutex);
CFIndex numLoggers = CFArrayGetCount(sLoggersList);
for (CFIndex i=0; i < numLoggers; i++)
LoggerFlush((Logger *) CFArrayGetValueAtIndex(sLoggersList, i), NO);
pthread_mutex_unlock(&sLoggersListMutex);
}
void LoggerFlush(Logger *logger, BOOL waitForConnection)
{
// Special case: if nothing has ever been logged, don't bother
if (logger == NULL && sDefaultLogger == NULL)
return;
if (logger == NULL)
logger = LoggerGetDefaultLogger();
if (logger != NULL &&
pthread_self() != logger->workerThread &&
(logger->connected || logger->bufferFile != NULL || waitForConnection)) // TODO: change this test
{
pthread_mutex_lock(&logger->logQueueMutex);
if (CFArrayGetCount(logger->logQueue) > 0)
pthread_cond_wait(&logger->logQueueEmpty, &logger->logQueueMutex);
pthread_mutex_unlock(&logger->logQueueMutex);
}
}
#if LOGGER_DEBUG
static void LoggerDbg(CFStringRef format, ...)
{
// Internal debugging function
// (what do you think, that we use the Logger to debug itself ??)
if (format != NULL)
{
@autoreleasepool
{
va_list args;
va_start(args, format);
CFStringRef s = CFStringCreateWithFormatAndArguments(NULL, NULL, format, args);
va_end(args);
if (s != NULL)
{
CFShow(s);
CFRelease(s);
}
}
}
}
#endif
// -----------------------------------------------------------------------------
#pragma mark -
#pragma mark Main processing
// -----------------------------------------------------------------------------
static BOOL LoggerPrepareRunloopSource(Logger *logger, CFRunLoopSourceRef *outRef, void *callback)
{
// first call will also create the thread's runloop
CFRunLoopSourceContext context;
bzero(&context, sizeof(context));
context.info = logger;
context.perform = callback;
*outRef = CFRunLoopSourceCreate(NULL, 0, &context);
if (*outRef == NULL)
{
// This NSLog is intentional as this failure MUST be logged to console
NSLog(@"*** NSLogger: worker thread failed creating runloop source");
return NO;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), *outRef, kCFRunLoopDefaultMode);
return YES;
}
static void LoggerDisposeRunloopSource(CFRunLoopSourceRef *sourceRef)
{
if (*sourceRef != NULL)
{
CFRunLoopSourceInvalidate(*sourceRef);
CFRelease(*sourceRef);
*sourceRef = NULL;
}
}
static void *LoggerWorkerThread(Logger *logger)
{
LOGGERDBG(CFSTR("Start LoggerWorkerThread"));
#if !TARGET_OS_IPHONE
// Register thread with Garbage Collector on Mac OS X if we're running an OS version that has GC
void (*registerThreadWithCollector_fn)(void);
registerThreadWithCollector_fn = (void(*)(void)) dlsym(RTLD_NEXT, "objc_registerThreadWithCollector");
if (registerThreadWithCollector_fn)
(*registerThreadWithCollector_fn)();
#endif
// access to the runloop sources is protected by our logQueue mutex
pthread_mutex_lock(&logger->logQueueMutex);
// Create the run loop source that signals when messages have been added to the runloop
// this will directly trigger a WriteMoreData() call, which will or won't write depending
// on whether we're connected and there's space available in the stream
if (!LoggerPrepareRunloopSource(logger, &logger->messagePushedSource, &LoggerWriteMoreData))
{
// Failing to create the runloop source for pushing messages is a major failure.
// This NSLog is intentional. We WANT console output in this case
NSLog(@"*** NSLogger: switching to console logging.");
logger->options |= kLoggerOption_LogToConsole;
logger->workerThread = NULL;
return NULL;
}
// Create the runloop source that lets us know when file buffering options change
LoggerPrepareRunloopSource(logger, &logger->bufferFileChangedSource, &LoggerFileBufferingOptionsChanged);
// Create the runloop source that lets us know when remote (host, Bonjour) settings change
LoggerPrepareRunloopSource(logger, &logger->remoteOptionsChangedSource, &LoggerRemoteSettingsChanged);
pthread_mutex_unlock(&logger->logQueueMutex);
// Create the buffering stream if needed
if (logger->bufferFile != NULL)
LoggerCreateBufferWriteStream(logger);
// Start Reachability (when needed), which determines when we take the next step
// (once Reachability status is known, we'll decide to either start Bonjour browsing or
// try connecting to a direct host)
LoggerStartReachabilityChecking(logger);
// Run logging thread until LoggerStop() is called
NSTimeInterval timeout = 0.05;
while (!logger->quit)
{
int result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout, true);
if (result == kCFRunLoopRunFinished || result == kCFRunLoopRunStopped)
break;
if (result == kCFRunLoopRunHandledSource)
timeout = 0;
else
timeout = fmax(0.05, timeout+0.005);
}
// Cleanup
LoggerStopBonjourBrowsing(logger);
LoggerStopReachabilityChecking(logger);
LoggerStopReconnectTimer(logger);
if (logger->logStream != NULL)
{
CFWriteStreamSetClient(logger->logStream, 0, NULL, NULL);
CFWriteStreamClose(logger->logStream);
CFRelease(logger->logStream);
logger->logStream = NULL;
}
if (logger->bufferWriteStream == NULL && logger->bufferFile != NULL)
{
// If there are messages in the queue and LoggerStop() was called and
// a buffer file was set just before LoggerStop() was called, flush
// the log queue to the buffer file
pthread_mutex_lock(&logger->logQueueMutex);
CFIndex outstandingMessages = CFArrayGetCount(logger->logQueue);
pthread_mutex_unlock(&logger->logQueueMutex);
if (outstandingMessages)
LoggerCreateBufferWriteStream(logger);
}
if (logger->bufferWriteStream != NULL)
{
CFWriteStreamClose(logger->bufferWriteStream);
CFRelease(logger->bufferWriteStream);
logger->bufferWriteStream = NULL;
}
LoggerDisposeRunloopSource(&logger->messagePushedSource);
LoggerDisposeRunloopSource(&logger->bufferFileChangedSource);
LoggerDisposeRunloopSource(&logger->remoteOptionsChangedSource);
// if the client ever tries to log again against us, make sure that logs at least
// go to console
logger->options |= kLoggerOption_LogToConsole;
LOGGERDBG(CFSTR("Stop LoggerWorkerThread"));
return NULL;
}
static CFStringRef LoggerCreateStringRepresentationFromBinaryData(CFDataRef data)
{
CFMutableStringRef s = CFStringCreateMutable(NULL, 0);
unsigned int offset = 0;
unsigned int dataLen = (unsigned int)CFDataGetLength(data);
char buffer[1+6+16*3+1+16+1+1+1];
buffer[0] = '\0';
const unsigned char *q = (unsigned char *)CFDataGetBytePtr(data);
if (dataLen == 1)
CFStringAppend(s, CFSTR("Raw data, 1 byte:\n"));
else
CFStringAppendFormat(s, NULL, CFSTR("Raw data, %u bytes:\n"), dataLen);
while (dataLen)
{
int i, j, b = sprintf(buffer," %04x: ", offset);
for (i=0; i < 16 && i < (int)dataLen; i++)
sprintf(&buffer[b+3*i], "%02x ", (int)q[i]);
for (j=i; j < 16; j++)
strncat(buffer, " ", 3);
b = (int)strlen(buffer);
buffer[b++] = '\'';
for (i=0; i < 16 && i < (int)dataLen; i++, q++)
{
if (*q >= 32 && *q < 128)
buffer[b++] = (char)*q;
else
buffer[b++] = ' ';
}
for (j=i; j < 16; j++)
buffer[b++] = ' ';
buffer[b++] = '\'';
buffer[b++] = '\n';
buffer[b] = 0;
CFStringRef bufferStr = CFStringCreateWithBytesNoCopy(NULL, (const UInt8 *)buffer, (CFIndex)strlen(buffer), kCFStringEncodingISOLatin1, false, kCFAllocatorNull);
CFStringAppend(s, bufferStr);
CFRelease(bufferStr);
dataLen -= (unsigned int)i;
offset += (unsigned int)i;
}
return s;
}
static void LoggerLogToConsole(CFDataRef data)
{
// Decode and log a message to the console. Doing this from the worker thread
// allow us to serialize logging, which is a benefit that NSLog() doesn't have.
// Only drawback is that we have to decode our own message, but that is a minor hassle.
if (data == NULL)
{
CFShow(CFSTR("LoggerLogToConsole: data is NULL"));
return;
}
struct timeval timestamp;
bzero(×tamp, sizeof(timestamp));
int type = LOGMSG_TYPE_LOG, contentsType = PART_TYPE_STRING;
int imgWidth=0, imgHeight=0;
CFStringRef message = NULL;
CFStringRef thread = NULL;
// decode message contents
uint8_t *p = (uint8_t *)CFDataGetBytePtr(data) + 4;
uint16_t partCount;
memcpy(&partCount, p, 2);
partCount = ntohs(partCount);
p += 2;
while (partCount--)
{
uint8_t partKey = *p++;
uint8_t partType = *p++;
uint32_t partSize;
if (partType == PART_TYPE_INT16)
partSize = 2;
else if (partType == PART_TYPE_INT32)
partSize = 4;
else if (partType == PART_TYPE_INT64)
partSize = 8;
else
{
memcpy(&partSize, p, 4);
p += 4;
partSize = ntohl(partSize);
}
CFTypeRef part = NULL;
uint32_t value32 = 0;
uint64_t value64 = 0;
if (partSize > 0)
{
if (partType == PART_TYPE_STRING)
{
// trim whitespace and newline at both ends of the string
uint8_t *q = p;
uint32_t l = partSize;
while (l && (*q == ' ' || *q == '\t' || *q == '\n' || *q == '\r')) {
q++;
l--;
}
uint8_t *r = q + l - 1;
while (l && (*r == ' ' || *r == '\t' || *r == '\n' || *r == '\r')) {
r--;
l--;
}
part = CFStringCreateWithBytesNoCopy(NULL, q, (CFIndex)l, kCFStringEncodingUTF8, false, kCFAllocatorNull);
}
else if (partType == PART_TYPE_BINARY)
{
part = CFDataCreateWithBytesNoCopy(NULL, p, (CFIndex)partSize, kCFAllocatorNull);
}
else if (partType == PART_TYPE_IMAGE)
{
// ignore image data, we can't log it to console
}
else if (partType == PART_TYPE_INT16)
{
value32 = ((uint32_t)p[0]) << 8 | (uint32_t)p[1];
}
else if (partType == PART_TYPE_INT32)
{
memcpy(&value32, p, 4);
value32 = ntohl(value32);
}
else if (partType == PART_TYPE_INT64)
{
memcpy(&value64, p, 8);
value64 = CFSwapInt64BigToHost(value64);
}
p += partSize;
}
switch (partKey)
{
case PART_KEY_MESSAGE_TYPE:
type = (int)value32;
break;
case PART_KEY_TIMESTAMP_S: // timestamp with seconds-level resolution
timestamp.tv_sec = (partType == PART_TYPE_INT64) ? (__darwin_time_t)value64 : (__darwin_time_t)value32;
break;
case PART_KEY_TIMESTAMP_MS: // millisecond part of the timestamp (optional)
timestamp.tv_usec = ((partType == PART_TYPE_INT64) ? (__darwin_suseconds_t)value64 : (__darwin_suseconds_t)value32) * 1000;
break;
case PART_KEY_TIMESTAMP_US: // microsecond part of the timestamp (optional)
timestamp.tv_usec = (partType == PART_TYPE_INT64) ? (__darwin_suseconds_t)value64 : (__darwin_suseconds_t)value32;
break;
case PART_KEY_THREAD_ID:
if (thread == NULL) // useless test, we know what we're doing but clang analyzer doesn't...
{
if (partType == PART_TYPE_INT32)
thread = CFStringCreateWithFormat(NULL, NULL, CFSTR("thread 0x%08x"), value32);
else if (partType == PART_TYPE_INT64)
thread = CFStringCreateWithFormat(NULL, NULL, CFSTR("thread 0x%qx"), value64);
else if (partType == PART_TYPE_STRING && part != NULL)
thread = CFRetain(part);
}
break;
case PART_KEY_MESSAGE:
if (part != NULL)
{
if (partType == PART_TYPE_STRING)
message = CFRetain(part);
else if (partType == PART_TYPE_BINARY)
message = LoggerCreateStringRepresentationFromBinaryData(part);
}
contentsType = partType;
break;
case PART_KEY_IMAGE_WIDTH:
imgWidth = (partType == PART_TYPE_INT32 ? (int)value32 : (int)value64);
break;
case PART_KEY_IMAGE_HEIGHT:
imgHeight = (partType == PART_TYPE_INT32 ? (int)value32 : (int)value64);
break;
default:
break;
}
if (part != NULL)
CFRelease(part);
}
// Prepare the final representation and log to console
CFMutableStringRef s = CFStringCreateMutable(NULL, 0);
char buf[32];
struct tm t;
gmtime_r(×tamp.tv_sec, &t);
strftime(buf, sizeof(buf)-1, "%T", &t);
CFStringRef ts = CFStringCreateWithBytesNoCopy(
NULL,
(const UInt8 *)buf,
(CFIndex)strlen(buf),
kCFStringEncodingASCII,
false,
kCFAllocatorNull);
CFStringAppend(s, ts);
CFRelease(ts);
if (contentsType == PART_TYPE_IMAGE)
message = CFStringCreateWithFormat(NULL, NULL, CFSTR("<image width=%d height=%d>"), imgWidth, imgHeight);
buf[0] = 0;
if (thread != NULL && CFStringGetLength(thread) < 16)
{
int n = 16 - (int)CFStringGetLength(thread);
memset(buf, ' ', (size_t)n);
buf[n] = 0;
}
CFStringAppendFormat(s, NULL, CFSTR(".%04d %s%@ | %@"),
(int)(timestamp.tv_usec / 1000),
buf, (thread == NULL) ? CFSTR("") : thread,
(message != NULL) ? message : CFSTR(""));
if (thread != NULL)
CFRelease(thread);
if (message != NULL)
CFRelease(message);
if (type == LOGMSG_TYPE_LOG || type == LOGMSG_TYPE_MARK)
CFShow(s);
CFRelease(s);
}
static void LoggerWriteMoreData(Logger *logger)
{
BOOL logToConsole = (logger->options & (kLoggerOption_LogToConsole | kLoggerOption_CaptureSystemConsole)) == kLoggerOption_LogToConsole;
if (!logger->connected)
{
if (logToConsole)
{
pthread_mutex_lock(&logger->logQueueMutex);
while (CFArrayGetCount(logger->logQueue))
{
LoggerLogToConsole((CFDataRef)CFArrayGetValueAtIndex(logger->logQueue, 0));
CFArrayRemoveValueAtIndex(logger->logQueue, 0);
}
pthread_mutex_unlock(&logger->logQueueMutex);
pthread_cond_broadcast(&logger->logQueueEmpty);
}
else if (logger->bufferWriteStream != NULL)
{
LoggerFlushQueueToBufferStream(logger, NO);