Realm-cocoa: Error Domain=io.realm Code=2 "Unable to open a realm at path

Created on 6 Mar 2019  路  32Comments  路  Source: realm/realm-cocoa

Getting this exception from realm:

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 
"Unable to open a realm at path '/var/mobile/Containers/Data/Application/E617FF40-6D77-4F3B-
8F3B-0DAC23C9C954/Documents/ApplicationData.realm.lock': open() failed: Operation not
 permitted." UserInfo={Error Code=2, NSFilePath=/var/mobile/Containers/Data/Application/E617FF40-
6D77-4F3B-8F3B-0DAC23C9C954/Documents/ApplicationData.realm.lock, 
Underlying=open("/var/mobile/Containers/Data/Application/E617FF40-6D77-4F3B-8F3B-
0DAC23C9C954/Documents/ApplicationData.realm.lock") failed: Operation not permitted, 
NSLocalizedDescription=Unable to open a realm at path 
'/var/mobile/Containers/Data/Application/E617FF40-6D77-4F3B-8F3B-
0DAC23C9C954/Documents/ApplicationData.realm.lock': open() failed: Operation not permitted.}: file 
/BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang_Fall2018/swiftlang_Fall2018-
1000.11.37.1/src/swift/stdlib/public/core/ErrorType.swift, line 184

This started in a version of our app 3 months ago. We have done realm schema changes and migrations in many of our releases including the one in which this crash started to show up.

I have gone through https://realm.io/docs/swift/latest/#using-realm-with-background-app-refresh, but found that there is mismatch between Realm's and Apple's documentation, specifically this part:

  • Realm
If your app attempts to do any work involving Realm while the device is locked and the 
NSFileProtection attributes of your Realm files are set to encrypt them (which is the case by default), 
an open() failed: Operation not permitted exception will be thrown.
  • Apple (https://www.apple.com/business/site/docs/iOS_Security_Guide.pdf)
This (NSFileProtectionCompleteUntilFirstUserAuthentication) is the default class for all third-party app 
data not otherwise assigned to a Data Protection class.

We do access realm when the app is in background (via background fetches and silent notifications). However, our crash numbers are quite high and it's hard to imagine them all happening due to NSFileProtectionCompleteUntilFirstUserAuthentication protection level (i.e. user restarting the device and our app waking up and accessing realm via background fetches or silent notifications before user unlocks).

Some other things to note:

  • We are not using Realm's encryption
  • We are not using any data protection capabilities in iOS
  • We are seeing almost a 1:1 correlation between number of users and number of crashes
  • We are not setting any explicit file protection level on the realm file url in our app

Goals

Understand when and why realm would throw this exception when using the default file protection level.

Expected Results

More details logs into why Operation not permitted.

Actual Results

Stack trace only tells open() failed: Operation not permitted.

Steps to Reproduce

Don't have repro steps yet

Code Sample

NA

Version of Realm and Tooling

Realm framework version: 3.13.1

Realm Object Server version: NA

Xcode version: 10.1 (10B61)

iOS/OSX version: 12.1.4 (16D57)

Dependency manager + version: Cocoapods 1.5.3

O-Community P-1-Required Pipeline-Waiting-for-User T-Help

Most helpful comment

@tgoyne thanks for jumping in!

To give some more context: this is happening for users who previously had accessed this ApplicationData.realm. Immediately after installing the app update, they start getting this exception when accessing realm.

One thing that I forgot to mention previously is that we do add new config.objectTypes to this realm and bump up the schemaVersion occasionally.

Also to re-iterate, we don鈥檛 change the file system permissions on realm's configuration.

This is the LOC where realm catches this exception:

catch (util::File::AccessError const& ex) {
        // Errors for `open()` include the path, but other errors don't. We
        // don't want two copies of the path in the error, so strip it out if it
        // appears, and then include it in our prefix.
        std::string underlying = ex.what();
        RealmFileException::Kind error_kind = RealmFileException::Kind::AccessError;
        // FIXME: Replace this with a proper specific exception type once Core adds support for it.
        if (underlying == "Bad or incompatible history type")
            error_kind = RealmFileException::Kind::BadHistoryError;
        auto pos = underlying.find(ex.get_path());
        if (pos != std::string::npos && pos > 0) {
            // One extra char at each end for the quotes
            underlying.replace(pos - 1, ex.get_path().size() + 2, "");
        }
        throw RealmFileException(error_kind, ex.get_path(),
                                 util::format("Unable to open a realm at path '%1': %2.", ex.get_path(), underlying), ex.what());

Can you provide any pointers about any potential causes this could happen?

All 32 comments

Any insights into what's going on here? We've been investigating this as a major crasher for our users.

I don't really know anything past what the error says and the documentation that you found. The only Realm-specific detail is that "ApplicationData.realm.lock" is the first of several files that we try to open when you try to open "ApplicationData.realm", and the open() call is failing with EPERM. There's nothing particularly unusual about that file or how we open it; presumably any other file in that directory which you tried to open at that time would fail in the same way.

@tgoyne thanks for jumping in!

To give some more context: this is happening for users who previously had accessed this ApplicationData.realm. Immediately after installing the app update, they start getting this exception when accessing realm.

One thing that I forgot to mention previously is that we do add new config.objectTypes to this realm and bump up the schemaVersion occasionally.

Also to re-iterate, we don鈥檛 change the file system permissions on realm's configuration.

This is the LOC where realm catches this exception:

catch (util::File::AccessError const& ex) {
        // Errors for `open()` include the path, but other errors don't. We
        // don't want two copies of the path in the error, so strip it out if it
        // appears, and then include it in our prefix.
        std::string underlying = ex.what();
        RealmFileException::Kind error_kind = RealmFileException::Kind::AccessError;
        // FIXME: Replace this with a proper specific exception type once Core adds support for it.
        if (underlying == "Bad or incompatible history type")
            error_kind = RealmFileException::Kind::BadHistoryError;
        auto pos = underlying.find(ex.get_path());
        if (pos != std::string::npos && pos > 0) {
            // One extra char at each end for the quotes
            underlying.replace(pos - 1, ex.get_path().size() + 2, "");
        }
        throw RealmFileException(error_kind, ex.get_path(),
                                 util::format("Unable to open a realm at path '%1': %2.", ex.get_path(), underlying), ex.what());

Can you provide any pointers about any potential causes this could happen?

We encounter frequent crashes on app startup. Actually it ranks as our most frequent crash right now. It's the same error message:

Crashed: com.apple.root.default-qos
`crash_info_entry_0Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 "Unable to open a realm at path '/private/var/mobile/Containers/Shared/AppGroup/XY/db.realm': open() failed: Operation not permitted." UserInfo={Error Code=2, NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/XY/db.realm, Underlying=open("/private/var/mobile/Containers/Shared/AppGroup/XY/db.realm") failed: Operation not permitted, NSLocalizedDescription=Unable to open a realm at path '/private/var/mobile/Containers/Shared/AppGroup/XY/db.realm': open() failed: Operation not permitted.}: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang_Fall2018/swiftlang_Fall2018-1000.11.42/src/swift/stdlib/public/core/ErrorType.swift, line 184 Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 "Unable to open a realm at path '/private/var/mobile`

Crash on startup. With the following stack traces:

Crashed: com.apple.root.default-qos
0  libswiftCore.dylib             0x106f44aa0 _stdlib_destroyTLS + 206472
1  libswiftCore.dylib             0x106f99848 swift_unexpectedError + 276
2  ExtensionKit              0x106c4b89c globalinit_33_99630046849355B5EF0B720EF7E8623D_func9 (RealmProvider.swift)
3  !                         0x1052031f0 RealmAdStore.getAll() (RealmAdStore.swift:44)
4  !                         0x105208784 partial apply for closure #1 in RealmAdStore.getAll(callback:) (RealmAdStore.swift:54)
5  !                         0x1050f0184 closure #1 in static Realm.autoReleasedBlockIfNecessary(callback:) (Realm+Extensions.swift:28)
6  !                         0x10557ac18 thunk for @callee_guaranteed () -> (@error @owned Error) (<compiler-generated>)
7  !                         0x1052087dc partial apply for thunk for @callee_guaranteed () -> (@error @owned Error) (<compiler-generated>)
8  libswiftObjectiveC.dylib       0x10744ae48 (Missing)
9  !                         0x105203580 RealmAdStore.getAll(callback:) (RealmAdStore.swift)
10 !                         0x105203964 protocol witness for AdStore.getAll(callback:) in conformance RealmAdStore (<compiler-generated>)
11 !                         0x1054d7b54 closure #1 in AdCatalogDataSource.loadItems(callback:) (AdCatalogDataSource.swift:84)
12 !                         0x105158cbc thunk for @escaping @callee_guaranteed () -> () (<compiler-generated>)
13 libdispatch.dylib              0x18993c374 _dispatch_call_block_and_release + 32
14 ???                            0x5cca018993d8f4 (Missing)
15 ???                            0x32d18189940550 (Missing)
16 ???                            0x3227818994c8c8 (Missing)
17 ???                            0x3a03818994d148 (Missing)
18 ???                            0x3efa8189b37b50 (Missing)
19 ???                            0x48af0189b3ddc4 (Missing)

What particularly stands out is that the same realm file is accessed too, to fetch some other data:

com.apple.root.default-qos
0  libswiftCore.dylib             0x106f44aa0 _stdlib_destroyTLS + 206472
1  libswiftCore.dylib             0x106f99848 swift_unexpectedError + 276
2  ExtensionKit              0x106c4b89c globalinit_33_99630046849355B5EF0B720EF7E8623D_func9 (RealmProvider.swift)
3  !                         0x10557b58c closure #1 in UserItemDao.getAllUserItems(callback:) (UserItemDao.swift:70)
4  !                         0x1050f0184 closure #1 in static Realm.autoReleasedBlockIfNecessary(callback:) (Realm+Extensions.swift:28)
5  !                         0x10557bf80 partial apply for thunk for @callee_guaranteed () -> (@error @owned Error) (<compiler-generated>)
6  libswiftObjectiveC.dylib       0x10744ae48 (Missing)
7  !                         0x10557b4e4 UserItemDao.getAllUserItems(callback:) (UserItemDao.swift)
8  !                         0x10557b99c protocol witness for UserItemStore.getAllUserItems(callback:) in conformance UserItemDao (<compiler-generated>)
9  !                         0x1054922b8 partial apply for closure #1 in UserItemListContentDataSource.loadItems(callback:) (UserItemListContentDataSource.swift:30)
10 !                         0x105158cbc thunk for @escaping @callee_guaranteed () -> () (<compiler-generated>)
11 libdispatch.dylib              0x18993c374 _dispatch_call_block_and_release + 32
12 ???                            0x5c91018993d8f4 (Missing)
13 ???                            0x1f580189940550 (Missing)
14 ???                            0x6bf4018994c8c8 (Missing)
15 ???                            0x377c018994d148 (Missing)
16 ???                            0xa460189b37b50 (Missing)
17 ???                            0x6fc70189b3ddc4 (Missing)

Maybe this gives some more insights...

I had the same problem, in my application has the possibility of the user log off and enter with another account, which generates another bank file of realm, the problem in my application happens when the user already has a database realm in the documents folder of the application and logs off, I imagine the realm problem has happened because realm is trying to access the primary database without having access to it.

This is my highest crasher. Using realm 3.15.0. Has anyone found a good workaround, other than deleting the database (which I can't do)?

Any update with this? Seeing the same problem here too

Any solution to this? Becoming increasingly frequent!

Using Realm 3.2.0

Domain: io.realm Code: 2 NSLocalizedDescription: Unable to open a realm at path '/var/mobile/Containers/Data/Application/640F17EA-33B5-4A0C-9F1D-79EC6CDC9E81/Documents/main.realm': Realm file decryption failed Path:Exception backtrace: 0 Realm 0x00000001032ea944 _ZNK5realm9SlabAlloc6verifyEv + 376 1 Realm 0x00000001032e9120 _ZN5realm9SlabAlloc11attach_fileERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEERNS0_6ConfigE + 4664 2 Realm 0x0000000103392bfc _ZN5realm11SharedGroup7do_openERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEbbNS_18SharedGroupOptionsE + 3144 3 Realm 0x00000001032b1768 _ZN5realm5_impl11RealmFriend13read_group_toERNS_5RealmENS_9VersionIDE + 4644 4 Realm 0x00000001032b13fc _ZN5realm5_impl11RealmFriend13read_group_toERNS_5RealmENS_9VersionIDE + 3768 5 Realm 0x00000001032aaaac _ZN5realm5Realm16open_with_configERKNS0_6C

Same issue, I would be interested in a any solution to avoid this crash at the start of the app

This appends in this function in the appDelegate

static func compactDefaultRealm() {


        if let defaultURL = Realm.Configuration.defaultConfiguration.fileURL {
            let defaultParentURL = defaultURL.deletingLastPathComponent()
            let compactedURL = defaultParentURL.appendingPathComponent("default-compact.realm")

            autoreleasepool {
            **let realm = try! Realm()**
            do {
                try realm.writeCopy(toFile: compactedURL)
            }
            catch {
                AppEventLogger.customEvent(name: "Error", attributes: ["func": "compactDefaultRealm",
                                                                       "line": "try RealmHelper.realm.writeCopy(toFile: compactedURL)",
                                                                       "error": error.localizedDescription])
                return
                }

            }
            do {
                try FileManager.default.removeItem(at: defaultURL)
                try FileManager.default.moveItem(at: compactedURL, to: defaultURL)
            }
            catch {
                AppEventLogger.customEvent(name: "Error (probably crash)", attributes: ["func": "compactDefaultRealm",
                                                                                        "line": "try FileManager.default.removeItem(at: defaultURL) // or next",
                                                                                        "error": error.localizedDescription])
            }
        }

    } 

note that my error is slightly different

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 "Unable to open a realm at path '/var/mobile/Containers/Data/Application/80BDC8A5-A594-4F58-AC48-E4DBE11782D2/Documents/default.realm': Invalid streaming format cookie (35454533953) Path:." UserInfo={Error Code=2, NSFilePath=/var/mobile/Containers/Data/Application/80BDC8A5-A594-4F58-AC48-E4DBE11782D2/Documents/default.realm, Underlying=Invalid streaming format cookie (35454533953) Path: /var/mobile/Containers/Data/Application/80BDC8A5-A594-4F58-AC48-E4DBE11782D2/Documents/default.realm, NSLocalizedDescription=Unable to open a realm at path '/var/mobile/Containers/Data/Application/80BDC8A5-A594-4F58-AC48-E4DBE11782D2/Documents/default.realm': Invalid streaming format cookie (35454533953) Path:.}: file [path to a personal files??]/RealmHelper.swift, line 123

@raphaels17

That code will fail catastrophically if the device is low on disk space: writeCopy() will create the file, write to it until the disk is full, then throw an error. We don't delete the incomplete file when writing fails, so the original file will then be replaced with the incomplete one and produce the error you're seeing.

The fix for this would be to either handle the error thrown by writeCopy() and delete the temporary file, or use compact on launch which should handle all of the error cases safely.

Error Domain=io.realm Code=2 "Unable to open a realm at path
'/var/mobile/Containers/Data/Application/154A001E-4F43-4BA3-98FF-F927ECE7B93B/Documents/default.realm': Invalid mnemonic.
 top_ref[0]: 0, top_ref[1]: 0, mnemonic: 0 0 0 0, fmt[0]: 0, fmt[1]: 0, flags: 0
Path:Exception backtrace:
0   Realm                               0x0000000107b5110c 

And so on

The more easy thing to debug this things (because I get sigaborts without stacktrace) so either you need to write in debugger bt 1 for thread 1 or better watch all RLM Exceptions RLMException, hit CMD+8and then add a symbolic breakpoint (step 1)

image

image

And when hit go one above the stack

image

This was the better way to find the error for me... also you can add an exception breakpoint instead, but it will catch a lot of throws, so you need to disable breakpoints untilyou will hit the point (and maybe it will catch others)

image

If you know how to make this breakpoint catch a specific exception like RLMException plz write it.

I am also getting this error, the path the generated successfully but I cannot able to goto that particular location path and also the realm exception error was occur like "Unable to open a realm at path". this kind of was happening simultaneously..

Error Domain=io.realm Code=2 "Unable to open a realm at path "

``

I am also getting this error after updating the realm (since 2020 June 5) from 3.16.1 to 5.0.2.
PLEASE FIX THIS

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 "Unable to open a realm at path '/var/mobile/Containers/Data/Application/90D60EF8-D05F-459E-A517-E26FDEF9622A/Documents/default.realm.lock': open() failed: Operation not permitted Path: /var/mobile/Containers/Data/Application/90D60EF8-D05F-459E-A517-E26FDEF9622A/Documents/default.realm.lock Exception backtrace: 0 Realm 0x00000001053dd59c _ZN5realm4util4File13open_internalERKNSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEENS1_10AccessModeENS1_10CreateModeEiPb + 712 1 Realm 0x000000010532e33c _ZN5realm2DB7do_openERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEbbNS_9DBOptionsE + 980 2 Realm 0x0000000105331544 _ZN5realm2DB4openERNS_11ReplicationENS_9DBOptionsE + 244 3 Realm 0x0000000105335a1c _ZN5realm2DB6createERNS_11ReplicationENS_9DBOptionsE + 392 4 Realm

I have the same issue using realm 4.4.1

crash_info_entry_0
Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=5 "Directory at path '/private/var/mobile/Containers/Shared/AppGroup/A243F9D4-00F3-4DC1-BFCF-DBC0006F7132/default.realm' does not exist." UserInfo={Error Code=5, NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/A243F9D4-00F3-4DC1-BFCF-DBC0006F7132/default.realm, Underlying=open("/private/var/mobile/Containers/Shared/AppGroup/A243F9D4-00F3-4DC1-BFCF-DBC0006F7132/default.realm") failed: No such file or directory Path: /private/var/mobile/Containers/Shared/AppGroup/A243F9D4-00F3-4DC1-BFCF-DBC0006F7132/default.realm Exception backtrace: 0 Realm 0x0000000107e1f4fc _ZN5realm4util4File13open_internalERKNSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEENS1_10AccessModeENS1_10CreateModeEiPb + 848 1 Realm 0x0000000107c7c2f8 _ZN5realm9SlabAlloc11attach_fileERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEERNS0_6ConfigE + 1440 2 R

Crashed: com.apple.main-thread
0 libswiftCore.dylib 0x1a48d9f00 $ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_SSAHSus6UInt32VtF + 796
1 libswiftCore.dylib 0x1a4908988 swift_unexpectedError + 432
2 Slatch 0x1050100bc DataService._realm.getter + 76 (DataService.swift:76)
3 Slatch 0x10502482c DataService.getUserSettings() + 886 (DataService.swift:886)
4 Slatch 0x104d635a4 static StoreRatingManager.firstTimeAppOpened() + 16 (StoreRatingManager.swift:16)
5 Slatch 0x104e6d97c static AppCoordinator.registartionRoute() + 25 (AppCoordinator.swift:25)
6 Slatch 0x104ecbfb8 closure #2 in closure #2 in closure #2 in LoadingViewController.alertRestore() + 99 (LoadingViewController.swift:99)
7 Slatch 0x104dd1654 thunk for @escaping @callee_guaranteed () -> () + 4365276756 (:4365276756)
8 libdispatch.dylib 0x1970ce524 + 16
9 libdispatch.dylib 0x197076e98 + 412
10 libdispatch.dylib 0x197087430 + 1276
11 libdispatch.dylib 0x197080498 + 620
12 CoreFoundation 0x1973866bc + 12
13 CoreFoundation 0x197381590 + 1724
14 CoreFoundation 0x197380ba8 CFRunLoopRunSpecific + 424
15 GraphicsServices 0x1a14f0344 GSEventRunModal + 160
16 UIKitCore 0x19b4bc3e4 UIApplicationMain + 1932
17 Slatch 0x104c76b18 main + 24 (CameraVC.swift:24)
18 libdyld.dylib 0x1972088f0 + 4

Any update on this issue?

Our application has hundreds of thousands of users. This crash is the number 1 cause of crashes currently. For this to be going on for so long for so many people is unacceptable. Will be looking at moving off Realm to some alternative forever and never using Realm for current or any future products if the inability to fix this continues.

!!!! REALM ERROR Initialization. 2 Error Domain=io.realm Code=2 "Unable to open a realm at path '/var/mobile/Containers/Data/Application/1726B833-4851-457B-A3CD-C80069C1BF66/Documents/default.realm': Realm file decryption failed Path:Exception backtrace:

@mungbeans2 We are sorry that you are encountering this issue. In order for us to try get to the bottom of this Could you tell me what version of Realm you are using and also could you provide a code sample that shows how you are using Realm and maybe some context of how you are using it (AppGroups, Multithreading, Encryption etc).

Thanks,
Lee

Lee, thanks for the prompt reply. Will post some more info later.

I am also facing the same issue and it is also the highest crasher for my application.
This crash happens in production build only. Never reproduce that issue in Dev/QA sessions.

I have also seen this error in CrashAnalytics and it was the only crash that was being reported in high volume. Could never reproduce using a Debug build and could never reproduce issue in-house just crash logs from customer usage. The best I can tell it happened after users upgraded our App even though the Realm version, and schema had not changed.

The one change we did make in the App update was to reference a realm object in AppDelegate that we hadn't before. In other words we were accessing Realm a lot sooner than in the prior version. Previously the first access to Realm was when logging into web site which required user input so Realm access was not so quick. This made me suspect there was a timing race condition associated with the Realm file access since I could not reproduce with Debug build. I really want to use Realm in my future iOS projects, but this issue which has been occurring for 1.5 years for us makes me gun shy. I guess the other possibility is that iOS messed up the file system permissions for sandbox when doing our App update.

I wonder if file permissions are getting messed up if user is updating your app from app store and realm is locked?
The fact that I can never reproduce the problem but customers can makes me think that when we push out an update and the high volume of users that update makes me think a small percentage of those hit an issue. I would not know how to debug an update issue. Does anyone else have thoughts?

I know it's not a complete solution but I've used two solutions in combination to eradicate the issue.

  1. I got this error because I was unable to open Realm because of not being able to fetch the Realm key from the keychain.
    Solution here : https://github.com/realm/realm-cocoa/issues/5615#issuecomment-580193005

  2. If Realm opening fails, delete and re-create instead of crashing.

private func deleteAndCreateRealm() -> Realm? {
        var realm: Realm?
        do {
            try FileManager.default.removeItem(at: GlobalStore.mainRealmConfig.fileURL!)
            realm = try Realm(configuration: GlobalStore.mainRealmConfig)
            realm?.autorefresh = true
        } catch let err {
            //Failed again
            Crashlytics.crashlytics().record(error: err)
        }

        return realm
    }

Having same problem but the error message is slightly different in my case.

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 "Unable to open a realm at path '/var/mobile/Containers/Data/Application/97C06C05-7655-4DD2-929A-DB5C4981C715/Documents/default.realm': Invalid top array (ref: 31048, size: 11)
Exception backtrace:
0   Realm                               0x0000000105d30808 _ZN5realm15InvalidDatabaseC2ERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEES9_ + 60
1   Realm                               0x0000000105d220e0 _

Having same problem but the error message is slightly different in my case.

Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 "Unable to open a realm at path '/var/mobile/Containers/Data/Application/97C06C05-7655-4DD2-929A-DB5C4981C715/Documents/default.realm': Invalid top array (ref: 31048, size: 11)
Exception backtrace:
0   Realm                               0x0000000105d30808 _ZN5realm15InvalidDatabaseC2ERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEES9_ + 60
1   Realm                               0x0000000105d220e0 _

having the same problem, any solution?

@norio-agoop @zrx89757 Can you please share the full crash log and what version of Realm your are using?

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2 "Unable to open a realm at path '/var/mobile/Containers/Data/Application/196168ED-146C-4398-935E-FB13A658DA9F/Documents/default.realm.lock': open() failed: Operation not permitted Path: /var/mobile/Containers/Data/Application/196168ED-146C-4398-935E-FB13A658DA9F/Documents/default.realm.lock Exception backtrace: 0 Realm 0x0000000103444638 _ZN5realm4util4File13open_internalERKNSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEENS1_10AccessModeENS1_10CreateModeEiPb + 712 1 Realm 0x0000000103377eb8 _ZN5realm2DB7do_openERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEbbNS_9DBOptionsE + 2716 2 Realm 0x000000010337ac6c _ZN5realm2DB4openERNS_11ReplicationENS_9DBOptionsE + 244 3 Realm 0x000000010337f598 _ZN5realm2DB6createERNS_11ReplicationENS_9DBOptionsE + 392 4 Realm

Facing frequently on app up
realm version : 5.5.0

@niralishaha25 are you using encryption? Does your app belong to an App Group? Have you got any file permissions set in your app?

Is anyone able to answer Lee's two questions above?

@niralishaha25 are you using encryption? Does your app belong to an App Group? Have you got any file permissions set in your app?

I am not using encryption.
Yes the app belongs to app group.
Not using any file permissions

I am experiencing the exact same problem. I have never encountered this problem myself in a development environment for several months, only on end-user devices where the problem would __occasionally__ appear.

2020-11-30T07:35:15-0500 critical: [RealmDB] failed to open, error: Unable to open a realm at path '/private/var/mobile/Containers/Shared/AppGroup/.../Realm/default.realm.lock': open() failed: Operation not permitted Path: /private/var/mobile/Containers/Shared/AppGroup/.../Realm/default.realm.lock
Exception backtrace:
0   Libraries_iOS                       0x0000000105250ed0 _ZN5realm4util4File13open_internalERKNSt3__112basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEENS1_10AccessModeENS1_10CreateModeEiPb + 744
1   Libraries_iOS                       0x000000010511f9c4 _ZN5realm2DB7do_openERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEbbNS_9DBOptionsE + 1084
2   Libraries_iOS                       0x0000000105122404 _ZN5realm2DB4openERNS_11ReplicationENS_9DBOptionsE + 184
3   Libraries_iOS                       0x00000001051262f4 _ZN5realm2DB6createERNS_11ReplicationENS_9DBOptionsE + 332
4   Libraries_iOS                       0x0000000104f311b4 _ZN5realm5_impl16RealmCoordinator7open_dbEv + 900
5   Libraries_iOS                       0x0000000104f302b0 _ZN5realm5_impl16RealmCoordinator12do_get_realmENS_5Realm6ConfigERNSt3__110shared_ptrIS2_EENS_4util8OptionalINS_9VersionIDEEERNS8_17CheckedUniqueLockE + 68
6   Libraries_iOS                       0x0000000104f3011c _ZN5realm5_impl16RealmCoordinator9get_realmENS_5Realm6ConfigENS_4util8OptionalINS_9VersionIDEEE + 480
7   Libraries_iOS                       0x0000000104f777dc _ZN5realm5Realm16get_shared_realmENS0_6ConfigE + 120
8   Libraries_iOS                       0x0000000105034878 _Z26RLMRealmTranslateExceptionPU15__autoreleasingP7NSError + 2664
9   Libraries_iOS                       0x000000010506e168 _Z19RLMISO8601Formatterv + 167516
10  Libraries_iOS                       0x0000000104d6916c Libraries_iOS + 119148
11  Libraries_iOS                       0x0000000104d681e8 Libraries_iOS + 115176
12  WidgetExtension                     0x00000001048ef858 WidgetExtension + 211032
...

From the crash logs, it appears that when the iOS 14 Widget (not main app) is launched (in init() of my @main WidgetBundle struct, main-thread), try Realm() fails to open the database causing the crash.

The database files are always located in a fixed directory in the AppGroup. Following is the launch code of my widget extension:

@main
struct MyWidgets: WidgetBundle {

    init() {
        // main thread

        // ...
        // set defaultConfiguration.fileURL to a fixed directory in App Group
        // ...

        let realm: Realm
        do {
            realm = try Realm()
            log.info(RealmDB.self, "opened")
        } catch {
            // crashed!!!
            log.critical(RealmDB.self, "failed to open, error: \(error.localizedDescription)")
            fatalError("failed to open realm database, error: \(error.localizedDescription)")
        }

        // ensure that File Protection is disabled after opening the database
        let folderPath = realm.configuration.fileURL!.deletingLastPathComponent().path
        try! FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.none],
                                                ofItemAtPath: folderPath)

        // ...

Should I move the File-Protection-Disable code to the front of try Realm()?

The realm-cocoa version is 10.1.4

The iOS 14 widget extension still crashes with a probability of about a few percent, even though I have set FileProtectionType.none for the directory before opening Realm.

Unable to open a realm at path '/private/var/mobile/Containers/Shared/AppGroup/.../Realm/default.realm.lock': open() failed:
Operation not permitted Path: /private/var/mobile/Containers/Shared/AppGroup/.../Realm/default.realm.lock

The realm-cocoa version is 10.5

Was this page helpful?
0 / 5 - 0 ratings