Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Segmentation fault when performing await realm.open(config) #4121

Closed
duncangroenewald opened this issue Nov 30, 2021 · 9 comments · Fixed by #4156
Closed

Segmentation fault when performing await realm.open(config) #4121

duncangroenewald opened this issue Nov 30, 2021 · 9 comments · Fixed by #4156
Assignees

Comments

@duncangroenewald
Copy link

duncangroenewald commented Nov 30, 2021

How frequently does the bug occur?

All the time

Description

Trying to load an existing local realm file into a test MongoDB Realm App and using a node.js script to do so. However when calling realm.open() we are getting a segmentation fault.

Node v16.13.0
realm-js v10.10.1

log in appears to work fine but the subsequent call results in a segmentation fault.

const realmConfig = {
        schema: target_realm_schema,
        sync: {
            user: app.currentUser,
            partitionValue: partitionKey,
            // The behavior to use when this is the first time opening a realm.
            newRealmFileBehavior: {
                type: "downloadBeforeOpen",
                timeout: 120,
                timeOutBehaviour: "openLocalRealm"
            },
            // The behavior to use when a realm file already exists locally,
            // i.e. you have previously opened the realm.
            existingRealmFileBehavior: {
                type: "openImmediately",
                timeout: 30,
                timeOutBehaviour: "openLocalRealm"
            },
        },
    };

    log("async open realm...")
    const target_realm = await Realm.open(realmConfig);

Anyone have any suggestions on how to debug the cause of the segmentation fault ?

Is the realm-js compatible with node v16.13.0 ?

Thanks

Stacktrace & log output

There is no stack trace.

Can you reproduce the bug?

Yes, always

Reproduction Steps

Script can be provided

Version

V10.10.1

What SDK flavour are you using?

MongoDB Realm (i.e. Sync, auth, functions)

Are you using encryption?

No, not using encryption

Platform OS and version(s)

macOS 12.0.1

Build environment

Which debugger for React Native: N/A

Here is the set fault

PID 90660 received SIGSEGV for address: 0x3
0 segfault-handler.node 0x0000000106bd1458 _ZL16segfault_handleriP9__siginfoPv + 272
1 libsystem_platform.dylib 0x000000019a6584e4 _sigtramp + 56
2 realm.node 0x000000010f7a5928 ZZN5realm6common6logger6Logger17build_sync_loggerERNSt3__18functionIFviNS3_12basic_stringIcNS3_11char_traitsIcEENS3_9allocatorIcEEEEEEEENKUlNS_4util6Logger5LevelEE_clESG

  • 172
    3 realm.node 0x000000010f7a5928 ZZN5realm6common6logger6Logger17build_sync_loggerERNSt3__18functionIFviNS3_12basic_stringIcNS3_11char_traitsIcEENS3_9allocatorIcEEEEEEEENKUlNS_4util6Logger5LevelEE_clESG + 172
    4 realm.node 0x000000010f7a57e0 ZNSt3__110__function6__funcIZN5realm6common6logger6Logger17build_sync_loggerERNS_8functionIFviNS_12basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEEEEEEUlNS2_4util6Logger5LevelEE_NSA_ISJ_EEFNS_10unique_ptrISH_NS_14default_deleteISH_EEEESI_EEclEOSI + 36
    5 realm.node 0x000000010f8d394c _ZNK5realm11SyncManager18create_sync_clientEv + 68
    6 realm.node 0x000000010f8d2a48 _ZN5realm11SyncManager11get_sessionENSt3__110shared_ptrINS_2DBEEERKNS_10SyncConfigE + 92
    7 realm.node 0x000000010f87731c _ZN5realm5_impl16RealmCoordinator19create_sync_sessionEv + 204
    8 realm.node 0x000000010f879d24 _ZN5realm5_impl16RealmCoordinator22get_synchronized_realmENS_5Realm6ConfigE + 88
    9 realm.node 0x000000010f850538 _ZN5realm5Realm22get_synchronized_realmENS0_6ConfigE + 108
    10 realm.node 0x000000010f6b85f8 _ZN5realm2js10RealmClassINS_4node5TypesEE16async_open_realmEN4Napi3EnvENS5_6ObjectERNS0_9ArgumentsIS3_EERNS0_11ReturnValueIS3_EE + 652
    11 realm.node 0x000000010f69ebf4 ZN5realm2js4wrapIXadL_ZNS0_10RealmClassINS_4node5TypesEE16async_open_realmEN4Napi3EnvENS6_6ObjectERNS0_9ArgumentsIS4_EERNS0_11ReturnValueIS4_EEEEEENS6_5ValueERKNS6_12CallbackInfoE + 244
    12 realm.node 0x000000010f6ed4b0 ZN4Napi7details12WrapCallbackIZNS_10ObjectWrapIN5realm4node13WrappedObjectINS3_2js10RealmClassINS4_5TypesEEEEEE27StaticMethodCallbackWrapperEP10napi_env__P20napi_callback_info__EUlvE_EEP12napi_value__T + 60
    13 realm.node 0x000000010f6ed468 ZN4Napi10ObjectWrapIN5realm4node13WrappedObjectINS1_2js10RealmClassINS2_5TypesEEEEEE27StaticMethodCallbackWrapperEP10napi_env__P20napi_callback_info
    + 28
    14 node 0x000000010242c6f8 _ZN6v8impl12_GLOBAL__N_123FunctionCallbackWrapper6InvokeERKN2v820FunctionCallbackInfoINS2_5ValueEEE + 104
    15 node 0x000000010262032c _ZN2v88internal25FunctionCallbackArguments4CallENS0_15CallHandlerInfoE + 276
    16 node 0x000000010261fe24 _ZN2v88internal12_GLOBAL__N_119HandleApiCallHelperILb0EEENS0_11MaybeHandleINS0_6ObjectEEEPNS0_7IsolateENS0_6HandleINS0_10HeapObjectEEESA_NS8_INS0_20FunctionTemplateInfoEEENS8_IS4_EENS0_16BuiltinArgumentsE + 468
    17 node 0x000000010261f6b0 _ZN2v88internal21Builtin_HandleApiCallEiPmPNS0_7IsolateE + 228
    18 node 0x0000000102d5d1cc Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit + 108
    19 node 0x0000000102cf0d18 Builtins_InterpreterEntryTrampoline + 248
    20 node 0x0000000102da3700 Builtins_PromiseConstructor + 2176
    21 node 0x0000000102cedf50 Builtins_JSBuiltinsConstructStub + 368
    22 node 0x0000000102dec070 Builtins_ConstructHandler + 656
    23 node 0x0000000102cf0d18 Builtins_InterpreterEntryTrampoline + 248
    24 node 0x0000000102cf0d18 Builtins_InterpreterEntryTrampoline + 248
    25 node 0x0000000102cf0d18 Builtins_InterpreterEntryTrampoline + 248
    26 node 0x0000000102d20314 Builtins_AsyncFunctionAwaitResolveClosure + 84
    27 node 0x0000000102da51b8 Builtins_PromiseFulfillReactionJob + 56
    28 node 0x0000000102d126f4 Builtins_RunMicrotasks + 596
    29 node 0x0000000102cee9e4 Builtins_JSRunMicrotasksEntry + 164
    30 node 0x00000001026c31e8 _ZN2v88internal12_GLOBAL__N_16InvokeEPNS0_7IsolateERKNS1_12InvokeParamsE + 2332
    31 node 0x00000001026c361c _ZN2v88internal12_GLOBAL__N_118InvokeWithTryCatchEPNS0_7IsolateERKNS1_12InvokeParamsE + 88
@duncangroenewald
Copy link
Author

@steffenagger - can you take a look at this issue - I see you fixed a similar one a while back. It seems all our Node scripts are broken now. Note that the MongoDB Realm App has no schema defined and is set to be in Development mode.

@duncangroenewald
Copy link
Author

Here is a simple script to just connect to the MongoDB Realm AppID. It seems to crash no matter what AppID I try using.

const appId = '';
const username = ''; // this is the user doing the copy
const password = '';

const Realm = require('realm');
const io = require('console-read-write');
const exists = require('realm');

const SegfaultHandler = require('segfault-handler');
SegfaultHandler.registerHandler('crash.log');

const partitionKey = 'default'; // the partition key (_partitionKey)

var queryRealm = async function (app) {
log("queryRealm()")

const realmConfig = {
    sync: {
        user: app.currentUser,
        partitionValue: partitionKey,
        // The behavior to use when this is the first time opening a realm.
        newRealmFileBehavior: {
            type: "downloadBeforeOpen",
            timeout: 30,
            timeOutBehaviour: "openLocalRealm"
        },
        // The behavior to use when a realm file already exists locally,
        // i.e. you have previously opened the realm.
        existingRealmFileBehavior: {
            type: "openImmediately"
        },
    },
};

const target_realm = new Realm(realmConfig);
//const target_realm = await Realm.open(realmConfig);
log("realm opened.")

target_realm.syncSession.addProgressNotification("upload", "reportIndefinitely", (transferred, tranferable) => log("UPLOAD: [" + transferred + "] " + tranferable));
target_realm.syncSession.addProgressNotification("download", "reportIndefinitely", (transferred, tranferable) => query(target_realm, transferred, tranferable));


const realm_schema = target_realm.schema;

var totalObjects = 0;
var totalLinks = 0;

log("==============");

for (const objSchema of realm_schema.sort((a, b) => a['name'] < b['name'])) {
    const allObjects = target_realm.objects(objSchema['name']);

    totalObjects += allObjects.length;

    var links = 0;

    // Count the links
    for (const targetObject of allObjects) {

        links += countLinks(targetObject, objSchema);
        
    }
    
    totalLinks += links;


    log(objSchema['name'] + ": " + allObjects.length + " (" + links + ")");


}

log("==============");

log("objects: "+ totalObjects);
log("links: "+ totalLinks);
log("==============");

log("Done (queryRealm)");
log("Enter to quit (queryRealm)");
await io.read();
log("Ended (queryRealm)");

}

async function run() {
log("run()");
try {

    const app = new Realm.App({ id: appId });
    log("app: " + app.id);
    Realm.App.Sync.setLogLevel(app, "trace");  // "all", "debug", "error", "info", "trace"
    Realm.App.Sync.setLogger(app, (level, message) => log("SYNC " + message));

    const credentials = new Realm.Credentials.emailPassword(username, password);

    const login = true

    if (login) {
        log("logging in...");
        await app.logIn(credentials);
        log("logged in.");
    } else {
        log("skipping log in");
    }
    //await copyRealm(app, source_realm_path);

    // Use this to query the new realm file
    // In theory delete the local folder called 'mongodb-realm' and run this and it should automatically download
    // data from the MongoDB Realm app instance in the cloud.

    await queryRealm(app);

    //await querySourceRealm();

} catch (errr) {
    error("Error: " + errr.name +", "+ errr.message);
}

log("Enter to quit");
io.write(await io.read());
log("Waiting to finish...");

}

function log(message) {
let date = Date().substring(4, 24);
console.log(date + " : " + message);
}
function error(message) {
log(message);
}

run().catch(err => {
error("Failed to open realm: "+ err.name);
throw err;
});

@sync-by-unito sync-by-unito bot assigned tomduncalf and unassigned tomduncalf Dec 1, 2021
@tomduncalf
Copy link
Contributor

Thanks for the bug report. I can reproduce the issue by calling Realm.App.Sync.setLogger(app, (level, message) => log("SYNC " + message)); – it seems that setting the logger causes a segmentation fault.

We will investigate this issue, for now are you able to try with your call to setLogger removed?

@tomduncalf
Copy link
Contributor

tomduncalf commented Dec 1, 2021

Initial investigation notes:

This is the repro code I am using:

const Realm = require(".")

const TestSchema = {
  name: "Test",
  properties: {
    _id: "objectId",
    name: "string",
    partition: "string",
  },
  primaryKey: "_id",
};

const app = new Realm.App({ id: "application-0-vqgmo" });
const creds = Realm.Credentials.anonymous();
const user = await app.logIn(creds);

Realm.App.Sync.setLogLevel(app, "trace"); // "all", "debug", "error", "info", "trace"
Realm.App.Sync.setLogger(app, (level, message) => console.log(`[${level}] ${message}`));

const realm = await Realm.open({
  schema: [TestSchema],
  sync: { user, partitionValue: "" },
});

@duncangroenewald
Copy link
Author

Thanks for the bug report. I can reproduce the issue by calling Realm.App.Sync.setLogger(app, (level, message) => log("SYNC " + message)); – it seems that setting the logger causes a segmentation fault.

We will investigate this issue, for now are you able to try with your call to setLogger removed?

Thanks, I will give that a try and let you know.

@duncangroenewald
Copy link
Author

@tomduncalf - thanks not using setLogger() fixed things. I will leave this issue open until a fix comes through. Thanks

@tomduncalf
Copy link
Contributor

Great, glad you were able to work around this issue for now!

@tomduncalf
Copy link
Contributor

It seems that this issue was introduced in 535bea5#diff-e112fb3700a88222a5435b4b508684f851f0e2b0ba7e0d2b7a024a23c5e18421 – nothing is taking ownership of log_fn any more, so it is going out of scope.

We should fix this issue and also add a unit test covering this function.

@fronck
Copy link

fronck commented Dec 20, 2021

Thanks for reporting this.
The fix has been merged in #4156 -- part of the upcoming v10.11.0 release.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 15, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants