xref: /aosp_15_r20/art/libnativebridge/include/nativebridge/native_bridge.h (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_LIBNATIVEBRIDGE_INCLUDE_NATIVEBRIDGE_NATIVE_BRIDGE_H_
18 #define ART_LIBNATIVEBRIDGE_INCLUDE_NATIVEBRIDGE_NATIVE_BRIDGE_H_
19 
20 #include <signal.h>
21 #include <stdbool.h>
22 #include <stdint.h>
23 #include <sys/types.h>
24 
25 #include "jni.h"
26 
27 #ifdef __cplusplus
28 namespace android {
29 extern "C" {
30 #endif  // __cplusplus
31 
32 enum JNICallType {
33   kJNICallTypeRegular = 1,
34   kJNICallTypeCriticalNative = 2,
35 };
36 
37 // Loads a shared library from the system linker namespace, suitable for
38 // platform libraries in /system/lib(64). If linker namespaces don't exist (i.e.
39 // on host), this simply calls dlopen().
40 void* OpenSystemLibrary(const char* path, int flags);
41 
42 struct NativeBridgeRuntimeCallbacks;
43 struct NativeBridgeRuntimeValues;
44 
45 // Function pointer type for sigaction. This is mostly the signature of a signal handler, except
46 // for the return type. The runtime needs to know whether the signal was handled or should be given
47 // to the chain.
48 typedef bool (*NativeBridgeSignalHandlerFn)(int, siginfo_t*, void*);  // NOLINT
49 
50 // Open the native bridge, if any. Should be called by Runtime::Init(). A null library filename
51 // signals that we do not want to load a native bridge.
52 bool LoadNativeBridge(const char* native_bridge_library_filename,
53                       const struct NativeBridgeRuntimeCallbacks* runtime_callbacks);
54 
55 // Quick check whether a native bridge will be needed. This is based off of the instruction set
56 // of the process.
57 bool NeedsNativeBridge(const char* instruction_set);
58 
59 // Do the early initialization part of the native bridge, if necessary. This should be done under
60 // high privileges.
61 bool PreInitializeNativeBridge(const char* app_data_dir, const char* instruction_set);
62 
63 // Prepare to fork from zygote. May be required to clean-up the enviroment, e.g.
64 // close emulated file descriptors, after doPreload() in app-zygote.
65 void PreZygoteForkNativeBridge();
66 
67 // Initialize the native bridge, if any. Should be called by Runtime::DidForkFromZygote. The JNIEnv*
68 // will be used to modify the app environment for the bridge.
69 bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set);
70 
71 // Unload the native bridge, if any. Should be called by Runtime::DidForkFromZygote.
72 void UnloadNativeBridge();
73 
74 // Check whether a native bridge is available (opened or initialized). Requires a prior call to
75 // LoadNativeBridge.
76 bool NativeBridgeAvailable();
77 
78 // Check whether a native bridge is available (initialized). Requires a prior call to
79 // LoadNativeBridge & InitializeNativeBridge.
80 bool NativeBridgeInitialized();
81 
82 // Load a shared library that is supported by the native bridge.
83 //
84 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
85 // Use NativeBridgeLoadLibraryExt() instead in namespace scenario.
86 void* NativeBridgeLoadLibrary(const char* libpath, int flag);
87 
88 // Get a native bridge trampoline for specified native method.
89 // This version is deprecated - please use NativeBridgeGetTrampoline2
90 void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty, uint32_t len);
91 
92 void* NativeBridgeGetTrampoline2(void* handle,
93                                  const char* name,
94                                  const char* shorty,
95                                  uint32_t len,
96                                  enum JNICallType jni_call_type);
97 
98 void* NativeBridgeGetTrampolineForFunctionPointer(const void* method,
99                                                   const char* shorty,
100                                                   uint32_t len,
101                                                   enum JNICallType jni_call_type);
102 
103 // True if native library paths are valid and is for an ABI that is supported by native bridge.
104 // The *libpath* must point to a library.
105 //
106 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
107 // Use NativeBridgeIsPathSupported() instead in namespace scenario.
108 bool NativeBridgeIsSupported(const char* libpath);
109 
110 // Returns the version number of the native bridge. This information is available after a
111 // successful LoadNativeBridge() and before closing it, that is, as long as NativeBridgeAvailable()
112 // returns true. Returns 0 otherwise.
113 uint32_t NativeBridgeGetVersion();
114 
115 // Returns a signal handler that the bridge would like to be managed. Only valid for a native
116 // bridge supporting the version 2 interface. Will return null if the bridge does not support
117 // version 2, or if it doesn't have a signal handler it wants to be known.
118 NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal);
119 
120 // Returns whether we have seen a native bridge error. This could happen because the library
121 // was not found, rejected, could not be initialized and so on.
122 //
123 // This functionality is mainly for testing.
124 bool NativeBridgeError();
125 
126 // Returns whether a given string is acceptable as a native bridge library filename.
127 //
128 // This functionality is exposed mainly for testing.
129 bool NativeBridgeNameAcceptable(const char* native_bridge_library_filename);
130 
131 // Decrements the reference count on the dynamic library handler. If the reference count drops
132 // to zero then the dynamic library is unloaded. Returns 0 on success and non-zero on error.
133 int NativeBridgeUnloadLibrary(void* handle);
134 
135 // Get last error message of native bridge when fail to load library or search symbol.
136 // This is reflection of dlerror() for native bridge.
137 const char* NativeBridgeGetError();
138 
139 struct native_bridge_namespace_t;
140 
141 // True if native library paths are valid and is for an ABI that is supported by native bridge.
142 // Different from NativeBridgeIsSupported(), the *path* here must be a directory containing
143 // libraries of an ABI.
144 //
145 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
146 // Use NativeBridgeIsSupported() instead in non-namespace scenario.
147 bool NativeBridgeIsPathSupported(const char* path);
148 
149 // Create new namespace in which native libraries will be loaded.
150 // NativeBridge's peer of android_create_namespace() of dynamic linker.
151 //
152 // The libraries in the namespace are searched by folowing order:
153 // 1. ld_library_path (Think of this as namespace-local LD_LIBRARY_PATH)
154 // 2. In directories specified by DT_RUNPATH of the "needed by" binary.
155 // 3. deault_library_path (This of this as namespace-local default library path)
156 //
157 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
158 // Should not use in non-namespace scenario.
159 struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
160     const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
161     const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent_ns);
162 
163 // Creates a link which shares some libraries from one namespace to another.
164 // NativeBridge's peer of android_link_namespaces() of dynamic linker.
165 //
166 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
167 // Should not use in non-namespace scenario.
168 bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
169                                 struct native_bridge_namespace_t* to,
170                                 const char* shared_libs_sonames);
171 
172 // Load a shared library with namespace key that is supported by the native bridge.
173 // NativeBridge's peer of android_dlopen_ext() of dynamic linker, only supports namespace
174 // extension.
175 //
176 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
177 // Use NativeBridgeLoadLibrary() instead in non-namespace scenario.
178 void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
179                                  struct native_bridge_namespace_t* ns);
180 
181 // Returns exported namespace by the name. This is a reflection of
182 // android_get_exported_namespace function. Introduced in v5.
183 struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name);
184 
185 // Native bridge interfaces to runtime.
186 struct NativeBridgeCallbacks {
187   // Version number of the interface.
188   uint32_t version;
189 
190   // Initialize native bridge. Native bridge's internal implementation must ensure MT safety and
191   // that the native bridge is initialized only once. Thus it is OK to call this interface for an
192   // already initialized native bridge.
193   //
194   // Parameters:
195   //   runtime_cbs [IN] the pointer to NativeBridgeRuntimeCallbacks.
196   // Returns:
197   //   true if initialization was successful.
198   bool (*initialize)(const struct NativeBridgeRuntimeCallbacks* runtime_cbs,
199                      const char* private_dir, const char* instruction_set);
200 
201   // Load a shared library that is supported by the native bridge.
202   //
203   // Parameters:
204   //   libpath [IN] path to the shared library
205   //   flag [IN] the stardard RTLD_XXX defined in bionic dlfcn.h
206   // Returns:
207   //   The opaque handle of the shared library if sucessful, otherwise NULL
208   //
209   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
210   // Use loadLibraryExt instead in namespace scenario.
211   void* (*loadLibrary)(const char* libpath, int flag);
212 
213   // Get a native bridge trampoline for specified native method. The trampoline has same
214   // signature as the native method.
215   //
216   // Parameters:
217   //   handle [IN] the handle returned from loadLibrary
218   //   shorty [IN] short descriptor of native method
219   //   len [IN] length of shorty
220   // Returns:
221   //   address of trampoline if successful, otherwise NULL
222   // Deprecated in v7
223   //   Starting with version 7 native bridge uses getTrampolineWithJNICallType
224   //   instead
225   void* (*getTrampoline)(void* handle, const char* name, const char* shorty, uint32_t len);
226 
227   // Check whether native library is valid and is for an ABI that is supported by native bridge.
228   //
229   // Parameters:
230   //   libpath [IN] path to the shared library
231   // Returns:
232   //   TRUE if library is supported by native bridge, FALSE otherwise
233   //
234   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
235   // Use isPathSupported instead in namespace scenario.
236   bool (*isSupported)(const char* libpath);
237 
238   // Provide environment values required by the app running with native bridge according to the
239   // instruction set.
240   //
241   // Parameters:
242   //   instruction_set [IN] the instruction set of the app
243   // Returns:
244   //   NULL if not supported by native bridge.
245   //   Otherwise, return all environment values to be set after fork.
246   const struct NativeBridgeRuntimeValues* (*getAppEnv)(const char* instruction_set);
247 
248   // Added callbacks in version 2.
249 
250   // Check whether the bridge is compatible with the given version. A bridge may decide not to be
251   // forwards- or backwards-compatible, and libnativebridge will then stop using it.
252   //
253   // Parameters:
254   //   bridge_version [IN] the version of libnativebridge.
255   // Returns:
256   //   true if the native bridge supports the given version of libnativebridge.
257   bool (*isCompatibleWith)(uint32_t bridge_version);
258 
259   // A callback to retrieve a native bridge's signal handler for the specified signal. The runtime
260   // will ensure that the signal handler is being called after the runtime's own handler, but before
261   // all chained handlers. The native bridge should not try to install the handler by itself, as
262   // that will potentially lead to cycles.
263   //
264   // Parameters:
265   //   signal [IN] the signal for which the handler is asked for. Currently, only SIGSEGV is
266   //                 supported by the runtime.
267   // Returns:
268   //   NULL if the native bridge doesn't use a handler or doesn't want it to be managed by the
269   //   runtime.
270   //   Otherwise, a pointer to the signal handler.
271   NativeBridgeSignalHandlerFn (*getSignalHandler)(int signal);
272 
273   // Added callbacks in version 3.
274 
275   // Decrements the reference count on the dynamic library handler. If the reference count drops
276   // to zero then the dynamic library is unloaded.
277   //
278   // Parameters:
279   //   handle [IN] the handler of a dynamic library.
280   //
281   // Returns:
282   //   0 on success, and nonzero on error.
283   int (*unloadLibrary)(void* handle);
284 
285   // Dump the last failure message of native bridge when fail to load library or search symbol.
286   //
287   // Parameters:
288   //
289   // Returns:
290   //   A string describing the most recent error that occurred when load library
291   //   or lookup symbol via native bridge.
292   const char* (*getError)();
293 
294   // Check whether library paths are supported by native bridge.
295   //
296   // Parameters:
297   //   library_path [IN] search paths for native libraries (directories separated by ':')
298   // Returns:
299   //   TRUE if libraries within search paths are supported by native bridge, FALSE otherwise
300   //
301   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
302   // Use isSupported instead in non-namespace scenario.
303   bool (*isPathSupported)(const char* library_path);
304 
305   // No longer used.
306   bool (*unused_initAnonymousNamespace)(const char*, const char*);
307 
308   // Create new namespace in which native libraries will be loaded.
309   // NativeBridge's peer of android_create_namespace() of dynamic linker.
310   //
311   // Parameters:
312   //   name [IN] the name of the namespace.
313   //   ld_library_path [IN] the first set of library search paths of the namespace.
314   //   default_library_path [IN] the second set of library search path of the namespace.
315   //   type [IN] the attribute of the namespace.
316   //   permitted_when_isolated_path [IN] the permitted path for isolated namespace(if it is).
317   //   parent_ns [IN] the pointer of the parent namespace to be inherited from.
318   // Returns:
319   //   native_bridge_namespace_t* for created namespace or nullptr in the case of error.
320   //
321   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
322   // Should not use in non-namespace scenario.
323   struct native_bridge_namespace_t* (*createNamespace)(const char* name,
324                                                        const char* ld_library_path,
325                                                        const char* default_library_path,
326                                                        uint64_t type,
327                                                        const char* permitted_when_isolated_path,
328                                                        struct native_bridge_namespace_t* parent_ns);
329 
330   // Creates a link which shares some libraries from one namespace to another.
331   // NativeBridge's peer of android_link_namespaces() of dynamic linker.
332   //
333   // Parameters:
334   //   from [IN] the namespace where libraries are accessed.
335   //   to [IN] the namespace where libraries are loaded.
336   //   shared_libs_sonames [IN] the libraries to be shared.
337   //
338   // Returns:
339   //   Whether successed or not.
340   //
341   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
342   // Should not use in non-namespace scenario.
343   bool (*linkNamespaces)(struct native_bridge_namespace_t* from,
344                          struct native_bridge_namespace_t* to, const char* shared_libs_sonames);
345 
346   // Load a shared library within a namespace.
347   // NativeBridge's peer of android_dlopen_ext() of dynamic linker, only supports namespace
348   // extension.
349   //
350   // Parameters:
351   //   libpath [IN] path to the shared library
352   //   flag [IN] the stardard RTLD_XXX defined in bionic dlfcn.h
353   //   ns [IN] the pointer of the namespace in which the library should be loaded.
354   // Returns:
355   //   The opaque handle of the shared library if sucessful, otherwise NULL
356   //
357   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
358   // Use loadLibrary instead in non-namespace scenario.
359   void* (*loadLibraryExt)(const char* libpath, int flag, struct native_bridge_namespace_t* ns);
360 
361   // Get native bridge version of vendor namespace.
362   // The vendor namespace is the namespace used to load vendor public libraries.
363   // With O release this namespace can be different from the default namespace.
364   // For the devices without enable vendor namespaces this function should return null
365   //
366   // Returns:
367   //   vendor namespace or null if it was not set up for the device
368   //
369   // Starting with v5 (Android Q) this function is no longer used.
370   // Use getExportedNamespace() below.
371   struct native_bridge_namespace_t* (*getVendorNamespace)();
372 
373   // Get native bridge version of exported namespace. Peer of
374   // android_get_exported_namespace(const char*) function.
375   //
376   // Returns:
377   //   exported namespace or null if it was not set up for the device
378   struct native_bridge_namespace_t* (*getExportedNamespace)(const char* name);
379 
380   // If native bridge is used in app-zygote (in doPreload()) this callback is
381   // required to clean-up the environment before the fork (see b/146904103).
382   void (*preZygoteFork)();
383 
384   // This replaces previous getTrampoline call starting with version 7 of the
385   // interface.
386   //
387   // Get a native bridge trampoline for specified native method. The trampoline
388   // has same signature as the native method.
389   //
390   // Parameters:
391   //   handle [IN] the handle returned from loadLibrary
392   //   shorty [IN] short descriptor of native method
393   //   len [IN] length of shorty
394   //   jni_call_type [IN] the type of JNI call
395   // Returns:
396   //   address of trampoline if successful, otherwise NULL
397   void* (*getTrampolineWithJNICallType)(void* handle,
398                                         const char* name,
399                                         const char* shorty,
400                                         uint32_t len,
401                                         enum JNICallType jni_call_type);
402 
403   // Get a native bridge trampoline for specified native method implementation pointer.
404   //
405   // Parameters:
406   //   method [IN] pointer to method implementation (ususally registered via call to
407   //   RegisterNatives).
408   //   shorty [IN] short descriptor of native method len [IN] length of shorty
409   //   jni_call_type [IN] the type of JNI call
410   // Returns:
411   //   address of trampoline if successful, otherwise NULL
412   void* (*getTrampolineForFunctionPointer)(const void* method,
413                                            const char* shorty,
414                                            uint32_t len,
415                                            enum JNICallType jni_call_type);
416 };
417 
418 // Runtime interfaces to native bridge.
419 struct NativeBridgeRuntimeCallbacks {
420   // Get shorty of a Java method. The shorty is supposed to be persistent in memory.
421   //
422   // Parameters:
423   //   env [IN] pointer to JNIenv.
424   //   mid [IN] Java methodID.
425   // Returns:
426   //   short descriptor for method.
427   const char* (*getMethodShorty)(JNIEnv* env, jmethodID mid);
428 
429   // Get number of native methods for specified class.
430   //
431   // Parameters:
432   //   env [IN] pointer to JNIenv.
433   //   clazz [IN] Java class object.
434   // Returns:
435   //   number of native methods.
436   uint32_t (*getNativeMethodCount)(JNIEnv* env, jclass clazz);
437 
438   // Get at most 'method_count' native methods for specified class 'clazz'. Results are outputed
439   // via 'methods' [OUT]. The signature pointer in JNINativeMethod is reused as the method shorty.
440   //
441   // Parameters:
442   //   env [IN] pointer to JNIenv.
443   //   clazz [IN] Java class object.
444   //   methods [OUT] array of method with the name, shorty, and fnPtr.
445   //   method_count [IN] max number of elements in methods.
446   // Returns:
447   //   number of method it actually wrote to methods.
448   uint32_t (*getNativeMethods)(JNIEnv* env, jclass clazz, JNINativeMethod* methods,
449                                uint32_t method_count);
450 };
451 
452 #ifdef __cplusplus
453 }  // extern "C"
454 }  // namespace android
455 #endif  // __cplusplus
456 
457 #endif  // ART_LIBNATIVEBRIDGE_INCLUDE_NATIVEBRIDGE_NATIVE_BRIDGE_H_
458