RLMUtil.mm 20 KB

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