@@ -1042,6 +1042,20 @@ pub extern "system" fn Java_org_apache_datafusion_SessionContext_getOptionNative
10421042 )
10431043}
10441044
1045+ /// Converts a raw JNI handle into a shared reference to a [`SessionContext`].
1046+ ///
1047+ /// # Safety for the unsafe usage
1048+ /// The caller must ensure `handle` was produced by `Box::into_raw(Box::new(ctx))`
1049+ /// in `createSessionContext` and has not yet been freed. The Java side zeroes
1050+ /// `nativeHandle` on `close()`, so the `handle == 0` guard in every JNI handler
1051+ /// ensures this invariant holds before `unwrap_context` is called.
1052+ fn unwrap_context ( handle : jlong ) -> JniResult < & ' static SessionContext > {
1053+ if handle == 0 {
1054+ return Err ( "SessionContext handle is null" . into ( ) ) ;
1055+ }
1056+ Ok ( unsafe { & * ( handle as * const SessionContext ) } )
1057+ }
1058+
10451059#[ no_mangle]
10461060pub extern "system" fn Java_org_apache_datafusion_SessionContext_tableExists < ' local > (
10471061 mut env : JNIEnv < ' local > ,
@@ -1050,13 +1064,7 @@ pub extern "system" fn Java_org_apache_datafusion_SessionContext_tableExists<'lo
10501064 name : JString < ' local > ,
10511065) -> jboolean {
10521066 try_unwrap_or_throw ( & mut env, 0 , |env| -> JniResult < jboolean > {
1053- if handle == 0 {
1054- return Err ( "SessionContext handle is null" . into ( ) ) ;
1055- }
1056- // SAFETY: handle is a valid Box<SessionContext> allocated by createSessionContext,
1057- // the null check above guards against zero, and the Java side zeroes nativeHandle
1058- // on close() so a closed context is caught before reaching here.
1059- let ctx = unsafe { & * ( handle as * const SessionContext ) } ;
1067+ let ctx = unwrap_context ( handle) ?;
10601068 let name: String = env. get_string ( & name) ?. into ( ) ;
10611069 Ok ( ctx. table_exist ( & name) ? as jboolean )
10621070 } )
@@ -1070,13 +1078,7 @@ pub extern "system" fn Java_org_apache_datafusion_SessionContext_deregisterTable
10701078 name : JString < ' local > ,
10711079) {
10721080 try_unwrap_or_throw ( & mut env, ( ) , |env| -> JniResult < ( ) > {
1073- if handle == 0 {
1074- return Err ( "SessionContext handle is null" . into ( ) ) ;
1075- }
1076- // SAFETY: handle is a valid Box<SessionContext> allocated by createSessionContext,
1077- // the null check above guards against zero, and the Java side zeroes nativeHandle
1078- // on close() so a closed context is caught before reaching here.
1079- let ctx = unsafe { & * ( handle as * const SessionContext ) } ;
1081+ let ctx = unwrap_context ( handle) ?;
10801082 let name: String = env. get_string ( & name) ?. into ( ) ;
10811083 ctx. deregister_table ( & name) ?;
10821084 Ok ( ( ) )
0 commit comments