RLMUtil.mm 17 KB

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