/
NSError-OBExtensions.m
353 lines (286 loc) · 12.9 KB
/
NSError-OBExtensions.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
// Copyright 2005-2017 Omni Development, Inc. All rights reserved.
//
// This software may only be used and reproduced according to the
// terms in the file OmniSourceLicense.html, which should be
// distributed with this project and can also be found at
// <http://www.omnigroup.com/developer/sourcecode/sourcelicense/>.
#import <OmniBase/NSError-OBExtensions.h>
#import <OmniBase/rcsid.h>
#import <OmniBase/assertions.h>
#import <OmniBase/OBUtilities.h>
#import <OmniBase/OBObject.h>
#import <OmniBase/OBLoadAction.h>
#import <Foundation/NSUserDefaults.h>
#import <Foundation/FoundationErrors.h>
#if !defined(TARGET_OS_IPHONE) || !TARGET_OS_IPHONE
#import <Security/Authorization.h> // for errAuthorizationCanceled
#endif
#import <Security/SecBase.h> // for errSecUserCanceled
RCS_ID("$Id$");
// This might be useful for non-debug builds too. These are only included in our errors, not Cocoa's, but if we use OBChainError when our code fails due to a Mac OS X framework call failing, we'll get information there.
#if 0 && defined(DEBUG)
#define INCLUDE_BACKTRACE_IN_ERRORS 1
#else
#define INCLUDE_BACKTRACE_IN_ERRORS 0
#endif
#if INCLUDE_BACKTRACE_IN_ERRORS
#include <execinfo.h> // For backtrace()
static NSString * const OBBacktraceAddressesErrorKey = @"com.omnigroup.framework.OmniBase.ErrorDomain.BacktraceAddresses";
static NSString * const OBBacktraceNamesErrorKey = @"com.omnigroup.framework.OmniBase.ErrorDomain.Backtrace";
#endif
static BOOL OBLogErrorCreations = NO;
static id (*original_initWithDomainCodeUserInfo)(NSError *self, SEL _cmd, NSString *domain, NSInteger code, NSDictionary *dict) = NULL;
@implementation NSError (OBExtensions)
static id _replacement_initWithDomain_code_userInfo(NSError *self, SEL _cmd, NSString *domain, NSInteger code, NSDictionary *dict)
{
#if INCLUDE_BACKTRACE_IN_ERRORS
{
const int maxFrames = 200;
void *frames[maxFrames];
int frameCount = backtrace(frames, maxFrames);
if (frameCount > 0) {
NSData *frameData = [[NSData alloc] initWithBytes:frames length:sizeof(frames[0]) * frameCount];
if (dict) {
NSMutableDictionary *updatedInfo = [[NSMutableDictionary alloc] initWithDictionary:dict];
updatedInfo[OBBacktraceAddressesErrorKey] = frameData;
dict = updatedInfo;
} else {
dict = @{OBBacktraceAddressesErrorKey:frameData};
}
}
}
#endif
if (!(self = original_initWithDomainCodeUserInfo(self, _cmd, domain, code, dict)))
return nil;
OBRecordBacktraceWithContext("Error created", OBBacktraceBuffer_Generic, (__bridge const void *)self);
if (OBLogErrorCreations)
NSLog(@"Error created: %@", [self toPropertyList]);
return self;
}
OBPerformPosing(^{
OBLogErrorCreations = [[NSUserDefaults standardUserDefaults] boolForKey:@"OBLogErrorCreations"];
Class self = objc_getClass("NSError");
original_initWithDomainCodeUserInfo = (typeof(original_initWithDomainCodeUserInfo))OBReplaceMethodImplementation(self, @selector(initWithDomain:code:userInfo:), (IMP)_replacement_initWithDomain_code_userInfo);
});
- (NSError *)underlyingErrorWithDomain:(NSString *)domain;
{
NSError *error = self;
while (error) {
if ([[error domain] isEqualToString:domain])
return error;
error = [[error userInfo] objectForKey:NSUnderlyingErrorKey];
}
return nil;
}
- (NSError *)underlyingErrorWithDomain:(NSString *)domain code:(NSInteger)code;
{
NSError *error = self;
while (error) {
if ([[error domain] isEqualToString:domain] && [error code] == code)
return error;
error = [[error userInfo] objectForKey:NSUnderlyingErrorKey];
}
return nil;
}
// Returns YES if the error or any of its underlying errors has the indicated domain and code.
- (BOOL)hasUnderlyingErrorDomain:(NSString *)domain code:(NSInteger)code;
{
return ([self underlyingErrorWithDomain:domain code:code] != nil);
}
- (BOOL)causedByUserCancelling;
{
if ([self hasUnderlyingErrorDomain:NSCocoaErrorDomain code:NSUserCancelledError])
return YES;
// N.B. Don't consider NSURLErrorDomain/NSURLErrorUserCancelledAuthentication a generic user cancelled case.
// We added this in r164657, but it turns out that this can bubble out of the URL connection system both by programatic and user cancels.
// These errors will have to be filtered closer to the source, as necessary
#if 0
if ([self hasUnderlyingErrorDomain:NSURLErrorDomain code:NSURLErrorUserCancelledAuthentication])
return YES;
#endif
#if !defined(TARGET_OS_IPHONE) || !TARGET_OS_IPHONE
if ([self hasUnderlyingErrorDomain:NSOSStatusErrorDomain code:errAuthorizationCanceled])
return YES;
if ([self hasUnderlyingErrorDomain:NSOSStatusErrorDomain code:userCanceledErr])
return YES;
#endif
if ([self hasUnderlyingErrorDomain:NSOSStatusErrorDomain code:errSecUserCanceled])
return YES;
return NO;
}
- (BOOL)causedByMissingFile;
{
return [self hasUnderlyingErrorDomain:NSPOSIXErrorDomain code:ENOENT]
|| [self hasUnderlyingErrorDomain:NSCocoaErrorDomain code:NSFileNoSuchFileError]
#if !defined(TARGET_OS_IPHONE) || !TARGET_OS_IPHONE
|| [self hasUnderlyingErrorDomain:NSOSStatusErrorDomain code:fnfErr]
#endif
;
}
- (BOOL)causedByExistingFile;
{
return [self hasUnderlyingErrorDomain:NSCocoaErrorDomain code:NSFileWriteFileExistsError]
|| [self hasUnderlyingErrorDomain:NSPOSIXErrorDomain code:EEXIST];
}
- (BOOL)causedByUnreachableHost;
{
NSError *urlError = [self underlyingErrorWithDomain:NSURLErrorDomain];
if (urlError == nil)
return NO;
switch ([urlError code]) {
case NSURLErrorTimedOut:
case NSURLErrorCannotFindHost:
case NSURLErrorNetworkConnectionLost:
case NSURLErrorDNSLookupFailed:
case NSURLErrorNotConnectedToInternet:
case NSURLErrorCannotConnectToHost:
return YES;
default:
return NO;
}
}
#if !defined(TARGET_OS_WATCH) || !TARGET_OS_WATCH
- (BOOL)causedByNetworkConnectionLost;
{
return [self hasUnderlyingErrorDomain:(NSString *)kCFErrorDomainCFNetwork code:kCFURLErrorNetworkConnectionLost] || [self hasUnderlyingErrorDomain:NSURLErrorDomain code:NSURLErrorNetworkConnectionLost];
}
#endif
- (id)initWithPropertyList:(NSDictionary *)propertyList;
{
NSString *domain = [propertyList objectForKey:@"domain"];
NSNumber *code = [propertyList objectForKey:@"code"];
OBASSERT(domain != nil);
OBASSERT(code != nil);
NSDictionary *userInfo = [propertyList objectForKey:@"userInfo"];
if (userInfo) {
NSMutableDictionary *mappedUserInfo = [NSMutableDictionary dictionary];
for (NSString *key in userInfo) {
id valueObject = [userInfo objectForKey:key];
// This is lossy, but once something is plist-ified, we can't be sure where it came from.
if ([key isEqualToString:NSUnderlyingErrorKey])
valueObject = [[NSError alloc] initWithPropertyList:valueObject];
else if ([key isEqualToString:NSRecoveryAttempterErrorKey] && [valueObject isKindOfClass:[NSString class]])
continue; // We can't turn an NSString back into a valid -recoveryAttempter object
[mappedUserInfo setObject:valueObject forKey:key];
}
userInfo = mappedUserInfo;
}
return [self initWithDomain:domain code:[code intValue] userInfo:userInfo];
}
static id _mapUserInfoValueToPlistValue(id valueObject)
{
if (!valueObject)
return @"<nil>";
// Handle some specific non-plist values
if ([valueObject isKindOfClass:[NSError class]])
return [(NSError *)valueObject toPropertyList];
if ([valueObject isKindOfClass:[NSURL class]])
return [valueObject absoluteString];
// Handle containers explicitly since they might contain non-plist values
// Map sets to arrays since NSSet isn't a plist type.
if ([valueObject isKindOfClass:[NSArray class]] || [valueObject isKindOfClass:[NSSet class]]) {
NSMutableArray *mapped = [NSMutableArray array];
for (id unmappedValue in (id <NSFastEnumeration>)valueObject) {
id mappedValue = _mapUserInfoValueToPlistValue(unmappedValue);
OBASSERT(mappedValue); // mapping returns something for nil
[mapped addObject:mappedValue];
}
return mapped;
}
if ([valueObject isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *mapped = [NSMutableDictionary dictionary];
[(NSDictionary *)valueObject enumerateKeysAndObjectsUsingBlock:^(NSString *key, id unmappedValue, BOOL *stop) {
if ([key isEqualToString:NSRecoveryAttempterErrorKey]) {
// Convert to a minimal plist value for logging/debugging
[mapped setObject:[valueObject shortDescription] forKey:NSRecoveryAttempterErrorKey];
return;
}
#if INCLUDE_BACKTRACE_IN_ERRORS
if ([key isEqualToString:OBBacktraceAddressesErrorKey]) {
// Transform this to symbol names when actually interested in it.
NSData *frameData = unmappedValue;
const void* const* frames = [frameData bytes];
NSUInteger frameCount = [frameData length] / sizeof(frames[0]);
OBASSERT(frameCount < INT_MAX); // since backtrace_symbols only takes int.
char **names = backtrace_symbols((void* const* )frames, (int)frameCount);
if (names) {
NSMutableArray *namesArray = [NSMutableArray array];
for (NSUInteger nameIndex = 0; nameIndex < frameCount; nameIndex++)
[namesArray addObject:[NSString stringWithCString:names[nameIndex] encoding:NSUTF8StringEncoding]];
free(names);
[mapped setObject:namesArray forKey:OBBacktraceNamesErrorKey];
return;
}
}
#endif
id mappedValue = _mapUserInfoValueToPlistValue(unmappedValue);
[mapped setObject:mappedValue forKey:key];
}];
return mapped;
}
// We can only bring along plist-able values (so, for example, no NSRecoveryAttempterErrorKey).
if (![NSPropertyListSerialization propertyList:valueObject isValidForFormat:NSPropertyListXMLFormat_v1_0]) {
#ifdef DEBUG
NSLog(@"'%@' of class '%@' is not a property list value.", valueObject, [valueObject class]);
#endif
return [valueObject description];
}
return valueObject;
}
- (NSDictionary *)toPropertyList;
{
NSMutableDictionary *plist = [NSMutableDictionary dictionary];
[plist setObject:[self domain] forKey:@"domain"];
[plist setObject:[NSNumber numberWithInteger:[self code]] forKey:@"code"];
NSDictionary *userInfo = [self userInfo];
if (userInfo)
[plist setObject:_mapUserInfoValueToPlistValue(userInfo) forKey:@"userInfo"];
return plist;
}
static NSString * const OFSuppressedErrorStack = @"com.omnigroup.OmniFoundation.SuppressedErrorStack"; // array of dictionaries
static NSString * const OFSuppressedErrorDomain = @"domain";
static NSString * const OFSuppressedErrorCode = @"code";
+ (void)suppressingLogsWithUnderlyingDomain:(NSString *)domain code:(NSInteger)code action:(void (^ NS_NOESCAPE)(void))action;
{
NSMutableDictionary *threadInfo = [[NSThread currentThread] threadDictionary];
NSMutableArray *suppressionStack = threadInfo[OFSuppressedErrorStack];
if (!suppressionStack) {
suppressionStack = [NSMutableArray new];
threadInfo[OFSuppressedErrorStack] = suppressionStack;
}
NSDictionary *suppression = @{OFSuppressedErrorDomain:domain, OFSuppressedErrorCode:@(code)};
[suppressionStack addObject:suppression];
action();
OBASSERT([suppressionStack lastObject] == suppression);
[suppressionStack removeLastObject];
if ([suppressionStack count] == 0)
[threadInfo removeObjectForKey:OFSuppressedErrorStack];
}
- (void)log:(NSString *)format, ...;
{
va_list args;
va_start(args, format);
[self log:format arguments:args];
va_end(args);
}
- (void)log:(NSString *)format arguments:(va_list)arguments;
{
NSString *reason = [[NSString alloc] initWithFormat:format arguments:arguments];
[self logWithReason:reason];
}
- (void)logWithReason:(NSString *)reason;
{
if ([self causedByUserCancelling])
return;
NSMutableArray *suppressionStack = [[NSThread currentThread] threadDictionary][OFSuppressedErrorStack];
if (suppressionStack) {
NSString *domain = self.domain;
NSNumber *code = @(self.code);
for (NSDictionary *suppression in suppressionStack) {
if ([domain isEqual:suppression[OFSuppressedErrorDomain]] && [code isEqual:suppression[OFSuppressedErrorCode]])
return;
}
}
NSLog(@"%@: %@", reason, [self toPropertyList]);
}
@end