RLMUtil.mm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. #import "RLMUtil.hpp"
  19. #import "RLMArray_Private.hpp"
  20. #import "RLMListBase.h"
  21. #import "RLMObjectSchema_Private.hpp"
  22. #import "RLMObjectStore.h"
  23. #import "RLMObject_Private.hpp"
  24. #import "RLMProperty_Private.h"
  25. #import "RLMSchema_Private.h"
  26. #import "RLMSwiftSupport.h"
  27. #import "shared_realm.hpp"
  28. #if REALM_ENABLE_SYNC
  29. #import "RLMSyncUtil.h"
  30. #endif
  31. #import <realm/mixed.hpp>
  32. #import <realm/table_view.hpp>
  33. #include <sys/sysctl.h>
  34. #include <sys/types.h>
  35. #if !defined(REALM_COCOA_VERSION)
  36. #import "RLMVersion.h"
  37. #endif
  38. static inline bool numberIsInteger(__unsafe_unretained NSNumber *const obj) {
  39. char data_type = [obj objCType][0];
  40. return data_type == *@encode(bool) ||
  41. data_type == *@encode(char) ||
  42. data_type == *@encode(short) ||
  43. data_type == *@encode(int) ||
  44. data_type == *@encode(long) ||
  45. data_type == *@encode(long long) ||
  46. data_type == *@encode(unsigned short) ||
  47. data_type == *@encode(unsigned int) ||
  48. data_type == *@encode(unsigned long) ||
  49. data_type == *@encode(unsigned long long);
  50. }
  51. static inline bool numberIsBool(__unsafe_unretained NSNumber *const obj) {
  52. // @encode(BOOL) is 'B' on iOS 64 and 'c'
  53. // objcType is always 'c'. Therefore compare to "c".
  54. if ([obj objCType][0] == 'c') {
  55. return true;
  56. }
  57. if (numberIsInteger(obj)) {
  58. int value = [obj intValue];
  59. return value == 0 || value == 1;
  60. }
  61. return false;
  62. }
  63. static inline bool numberIsFloat(__unsafe_unretained NSNumber *const obj) {
  64. char data_type = [obj objCType][0];
  65. return data_type == *@encode(float) ||
  66. data_type == *@encode(short) ||
  67. data_type == *@encode(int) ||
  68. data_type == *@encode(long) ||
  69. data_type == *@encode(long long) ||
  70. data_type == *@encode(unsigned short) ||
  71. data_type == *@encode(unsigned int) ||
  72. data_type == *@encode(unsigned long) ||
  73. data_type == *@encode(unsigned long long) ||
  74. // A double is like float if it fits within float bounds or is NaN.
  75. (data_type == *@encode(double) && (ABS([obj doubleValue]) <= FLT_MAX || isnan([obj doubleValue])));
  76. }
  77. static inline bool numberIsDouble(__unsafe_unretained NSNumber *const obj) {
  78. char data_type = [obj objCType][0];
  79. return data_type == *@encode(double) ||
  80. data_type == *@encode(float) ||
  81. data_type == *@encode(short) ||
  82. data_type == *@encode(int) ||
  83. data_type == *@encode(long) ||
  84. data_type == *@encode(long long) ||
  85. data_type == *@encode(unsigned short) ||
  86. data_type == *@encode(unsigned int) ||
  87. data_type == *@encode(unsigned long) ||
  88. data_type == *@encode(unsigned long long);
  89. }
  90. static inline RLMArray *asRLMArray(__unsafe_unretained id const value) {
  91. return RLMDynamicCast<RLMArray>(value) ?: RLMDynamicCast<RLMListBase>(value)._rlmArray;
  92. }
  93. static inline bool checkArrayType(__unsafe_unretained RLMArray *const array,
  94. RLMPropertyType type, bool optional,
  95. __unsafe_unretained NSString *const objectClassName) {
  96. return array.type == type && array.optional == optional
  97. && (type != RLMPropertyTypeObject || [array.objectClassName isEqualToString:objectClassName]);
  98. }
  99. id (*RLMSwiftAsFastEnumeration)(id);
  100. id<NSFastEnumeration> RLMAsFastEnumeration(__unsafe_unretained id obj) {
  101. if (!obj) {
  102. return nil;
  103. }
  104. if ([obj conformsToProtocol:@protocol(NSFastEnumeration)]) {
  105. return obj;
  106. }
  107. if (RLMSwiftAsFastEnumeration) {
  108. return RLMSwiftAsFastEnumeration(obj);
  109. }
  110. return nil;
  111. }
  112. BOOL RLMValidateValue(__unsafe_unretained id const value,
  113. RLMPropertyType type, bool optional, bool array,
  114. __unsafe_unretained NSString *const objectClassName) {
  115. if (optional && !RLMCoerceToNil(value)) {
  116. return YES;
  117. }
  118. if (array) {
  119. if (auto rlmArray = asRLMArray(value)) {
  120. return checkArrayType(rlmArray, type, optional, objectClassName);
  121. }
  122. if (id enumeration = RLMAsFastEnumeration(value)) {
  123. // check each element for compliance
  124. for (id el in enumeration) {
  125. if (!RLMValidateValue(el, type, optional, false, objectClassName)) {
  126. return NO;
  127. }
  128. }
  129. return YES;
  130. }
  131. if (!value || value == NSNull.null) {
  132. return YES;
  133. }
  134. return NO;
  135. }
  136. switch (type) {
  137. case RLMPropertyTypeString:
  138. return [value isKindOfClass:[NSString class]];
  139. case RLMPropertyTypeBool:
  140. if ([value isKindOfClass:[NSNumber class]]) {
  141. return numberIsBool(value);
  142. }
  143. return NO;
  144. case RLMPropertyTypeDate:
  145. return [value isKindOfClass:[NSDate class]];
  146. case RLMPropertyTypeInt:
  147. if (NSNumber *number = RLMDynamicCast<NSNumber>(value)) {
  148. return numberIsInteger(number);
  149. }
  150. return NO;
  151. case RLMPropertyTypeFloat:
  152. if (NSNumber *number = RLMDynamicCast<NSNumber>(value)) {
  153. return numberIsFloat(number);
  154. }
  155. return NO;
  156. case RLMPropertyTypeDouble:
  157. if (NSNumber *number = RLMDynamicCast<NSNumber>(value)) {
  158. return numberIsDouble(number);
  159. }
  160. return NO;
  161. case RLMPropertyTypeData:
  162. return [value isKindOfClass:[NSData class]];
  163. case RLMPropertyTypeAny:
  164. return NO;
  165. case RLMPropertyTypeLinkingObjects:
  166. return YES;
  167. case RLMPropertyTypeObject: {
  168. // only NSNull, nil, or objects which derive from RLMObject and match the given
  169. // object class are valid
  170. RLMObjectBase *objBase = RLMDynamicCast<RLMObjectBase>(value);
  171. return objBase && [objBase->_objectSchema.className isEqualToString:objectClassName];
  172. }
  173. }
  174. @throw RLMException(@"Invalid RLMPropertyType specified");
  175. }
  176. void RLMThrowTypeError(__unsafe_unretained id const obj,
  177. __unsafe_unretained RLMObjectSchema *const objectSchema,
  178. __unsafe_unretained RLMProperty *const prop) {
  179. @throw RLMException(@"Invalid value '%@' of type '%@' for '%@%s'%s property '%@.%@'.",
  180. obj, [obj class],
  181. prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "",
  182. prop.array ? " array" : "", objectSchema.className, prop.name);
  183. }
  184. void RLMValidateValueForProperty(__unsafe_unretained id const obj,
  185. __unsafe_unretained RLMObjectSchema *const objectSchema,
  186. __unsafe_unretained RLMProperty *const prop,
  187. bool validateObjects) {
  188. // This duplicates a lot of the checks in RLMIsObjectValidForProperty()
  189. // for the sake of more specific error messages
  190. if (prop.array) {
  191. // nil is considered equivalent to an empty array for historical reasons
  192. // since we don't support null arrays (only arrays containing null),
  193. // it's not worth the BC break to change this
  194. if (!obj || obj == NSNull.null) {
  195. return;
  196. }
  197. id enumeration = RLMAsFastEnumeration(obj);
  198. if (!enumeration) {
  199. @throw RLMException(@"Invalid value (%@) for '%@%s' array property '%@.%@': value is not enumerable.",
  200. obj, prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "",
  201. objectSchema.className, prop.name);
  202. }
  203. if (!validateObjects && prop.type == RLMPropertyTypeObject) {
  204. return;
  205. }
  206. if (RLMArray *array = asRLMArray(obj)) {
  207. if (!checkArrayType(array, prop.type, prop.optional, prop.objectClassName)) {
  208. @throw RLMException(@"RLMArray<%@%s> does not match expected type '%@%s' for property '%@.%@'.",
  209. array.objectClassName ?: RLMTypeToString(array.type), array.optional ? "?" : "",
  210. prop.objectClassName ?: RLMTypeToString(prop.type), prop.optional ? "?" : "",
  211. objectSchema.className, prop.name);
  212. }
  213. return;
  214. }
  215. for (id value in enumeration) {
  216. if (!RLMValidateValue(value, prop.type, prop.optional, false, prop.objectClassName)) {
  217. RLMThrowTypeError(value, objectSchema, prop);
  218. }
  219. }
  220. return;
  221. }
  222. // For create() we want to skip the validation logic for objects because
  223. // we allow much fuzzier matching (any KVC-compatible object with at least
  224. // all the non-defaulted fields), and all the logic for that lives in the
  225. // object store rather than here
  226. if (prop.type == RLMPropertyTypeObject && !validateObjects) {
  227. return;
  228. }
  229. if (RLMIsObjectValidForProperty(obj, prop)) {
  230. return;
  231. }
  232. RLMThrowTypeError(obj, objectSchema, prop);
  233. }
  234. BOOL RLMIsObjectValidForProperty(__unsafe_unretained id const obj,
  235. __unsafe_unretained RLMProperty *const property) {
  236. return RLMValidateValue(obj, property.type, property.optional, property.array, property.objectClassName);
  237. }
  238. NSDictionary *RLMDefaultValuesForObjectSchema(__unsafe_unretained RLMObjectSchema *const objectSchema) {
  239. if (!objectSchema.isSwiftClass) {
  240. return [objectSchema.objectClass defaultPropertyValues];
  241. }
  242. NSMutableDictionary *defaults = nil;
  243. if ([objectSchema.objectClass isSubclassOfClass:RLMObject.class]) {
  244. defaults = [NSMutableDictionary dictionaryWithDictionary:[objectSchema.objectClass defaultPropertyValues]];
  245. }
  246. else {
  247. defaults = [NSMutableDictionary dictionary];
  248. }
  249. RLMObject *defaultObject = [[objectSchema.objectClass alloc] init];
  250. for (RLMProperty *prop in objectSchema.properties) {
  251. if (!defaults[prop.name] && defaultObject[prop.name]) {
  252. defaults[prop.name] = defaultObject[prop.name];
  253. }
  254. }
  255. return defaults;
  256. }
  257. static NSException *RLMException(NSString *reason, NSDictionary *additionalUserInfo) {
  258. NSMutableDictionary *userInfo = @{RLMRealmVersionKey: REALM_COCOA_VERSION,
  259. RLMRealmCoreVersionKey: @REALM_VERSION}.mutableCopy;
  260. if (additionalUserInfo != nil) {
  261. [userInfo addEntriesFromDictionary:additionalUserInfo];
  262. }
  263. NSException *e = [NSException exceptionWithName:RLMExceptionName
  264. reason:reason
  265. userInfo:userInfo];
  266. return e;
  267. }
  268. NSException *RLMException(NSString *fmt, ...) {
  269. va_list args;
  270. va_start(args, fmt);
  271. NSException *e = RLMException([[NSString alloc] initWithFormat:fmt arguments:args], @{});
  272. va_end(args);
  273. return e;
  274. }
  275. NSException *RLMException(std::exception const& exception) {
  276. return RLMException(@"%s", exception.what());
  277. }
  278. NSError *RLMMakeError(RLMError code, std::exception const& exception) {
  279. return [NSError errorWithDomain:RLMErrorDomain
  280. code:code
  281. userInfo:@{NSLocalizedDescriptionKey: @(exception.what()),
  282. @"Error Code": @(code)}];
  283. }
  284. NSError *RLMMakeError(RLMError code, const realm::util::File::AccessError& exception) {
  285. return [NSError errorWithDomain:RLMErrorDomain
  286. code:code
  287. userInfo:@{NSLocalizedDescriptionKey: @(exception.what()),
  288. NSFilePathErrorKey: @(exception.get_path().c_str()),
  289. @"Error Code": @(code)}];
  290. }
  291. NSError *RLMMakeError(RLMError code, const realm::RealmFileException& exception) {
  292. NSString *underlying = @(exception.underlying().c_str());
  293. return [NSError errorWithDomain:RLMErrorDomain
  294. code:code
  295. userInfo:@{NSLocalizedDescriptionKey: @(exception.what()),
  296. NSFilePathErrorKey: @(exception.path().c_str()),
  297. @"Error Code": @(code),
  298. @"Underlying": underlying.length == 0 ? @"n/a" : underlying}];
  299. }
  300. NSError *RLMMakeError(std::system_error const& exception) {
  301. int code = exception.code().value();
  302. BOOL isGenericCategoryError = (exception.code().category() == std::generic_category());
  303. NSString *category = @(exception.code().category().name());
  304. NSString *errorDomain = isGenericCategoryError ? NSPOSIXErrorDomain : RLMUnknownSystemErrorDomain;
  305. #if REALM_ENABLE_SYNC
  306. if (exception.code().category() == realm::sync::client_error_category()) {
  307. if (exception.code().value() == static_cast<int>(realm::sync::Client::Error::connect_timeout)) {
  308. errorDomain = NSPOSIXErrorDomain;
  309. code = ETIMEDOUT;
  310. }
  311. else {
  312. errorDomain = RLMSyncErrorDomain;
  313. }
  314. }
  315. #endif
  316. return [NSError errorWithDomain:errorDomain code:code
  317. userInfo:@{NSLocalizedDescriptionKey: @(exception.what()),
  318. @"Error Code": @(exception.code().value()),
  319. @"Category": category}];
  320. }
  321. void RLMSetErrorOrThrow(NSError *error, NSError **outError) {
  322. if (outError) {
  323. *outError = error;
  324. }
  325. else {
  326. NSString *msg = error.localizedDescription;
  327. if (error.userInfo[NSFilePathErrorKey]) {
  328. msg = [NSString stringWithFormat:@"%@: %@", error.userInfo[NSFilePathErrorKey], error.localizedDescription];
  329. }
  330. @throw RLMException(msg, @{NSUnderlyingErrorKey: error});
  331. }
  332. }
  333. BOOL RLMIsDebuggerAttached()
  334. {
  335. int name[] = {
  336. CTL_KERN,
  337. KERN_PROC,
  338. KERN_PROC_PID,
  339. getpid()
  340. };
  341. struct kinfo_proc info;
  342. size_t info_size = sizeof(info);
  343. if (sysctl(name, sizeof(name)/sizeof(name[0]), &info, &info_size, NULL, 0) == -1) {
  344. NSLog(@"sysctl() failed: %s", strerror(errno));
  345. return false;
  346. }
  347. return (info.kp_proc.p_flag & P_TRACED) != 0;
  348. }
  349. BOOL RLMIsRunningInPlayground() {
  350. return [[NSBundle mainBundle].bundleIdentifier hasPrefix:@"com.apple.dt.playground."];
  351. }
  352. id RLMMixedToObjc(realm::Mixed const& mixed) {
  353. switch (mixed.get_type()) {
  354. case realm::type_String:
  355. return RLMStringDataToNSString(mixed.get_string());
  356. case realm::type_Int:
  357. return @(mixed.get_int());
  358. case realm::type_Float:
  359. return @(mixed.get_float());
  360. case realm::type_Double:
  361. return @(mixed.get_double());
  362. case realm::type_Bool:
  363. return @(mixed.get_bool());
  364. case realm::type_Timestamp:
  365. return RLMTimestampToNSDate(mixed.get_timestamp());
  366. case realm::type_Binary:
  367. return RLMBinaryDataToNSData(mixed.get_binary());
  368. case realm::type_Link:
  369. case realm::type_LinkList:
  370. default:
  371. @throw RLMException(@"Invalid data type for RLMPropertyTypeAny property.");
  372. }
  373. }
  374. NSString *RLMDefaultDirectoryForBundleIdentifier(NSString *bundleIdentifier) {
  375. #if TARGET_OS_TV
  376. (void)bundleIdentifier;
  377. // tvOS prohibits writing to the Documents directory, so we use the Library/Caches directory instead.
  378. return NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
  379. #elif TARGET_OS_IPHONE && !TARGET_OS_MACCATALYST
  380. (void)bundleIdentifier;
  381. // On iOS the Documents directory isn't user-visible, so put files there
  382. return NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
  383. #else
  384. // On OS X it is, so put files in Application Support. If we aren't running
  385. // in a sandbox, put it in a subdirectory based on the bundle identifier
  386. // to avoid accidentally sharing files between applications
  387. NSString *path = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)[0];
  388. if (![[NSProcessInfo processInfo] environment][@"APP_SANDBOX_CONTAINER_ID"]) {
  389. if (!bundleIdentifier) {
  390. bundleIdentifier = [NSBundle mainBundle].bundleIdentifier;
  391. }
  392. if (!bundleIdentifier) {
  393. bundleIdentifier = [NSBundle mainBundle].executablePath.lastPathComponent;
  394. }
  395. path = [path stringByAppendingPathComponent:bundleIdentifier];
  396. // create directory
  397. [[NSFileManager defaultManager] createDirectoryAtPath:path
  398. withIntermediateDirectories:YES
  399. attributes:nil
  400. error:nil];
  401. }
  402. return path;
  403. #endif
  404. }
  405. NSDateFormatter *RLMISO8601Formatter() {
  406. // note: NSISO8601DateFormatter can't be used as it doesn't support milliseconds
  407. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  408. dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  409. dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
  410. dateFormatter.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
  411. return dateFormatter;
  412. }