• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 bool NativeBridgeIsNativeBridgeFunctionPointer(const void* method);
104 
105 // True if native library paths are valid and is for an ABI that is supported by native bridge.
106 // The *libpath* must point to a library.
107 //
108 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
109 // Use NativeBridgeIsPathSupported() instead in namespace scenario.
110 bool NativeBridgeIsSupported(const char* libpath);
111 
112 // Returns the version number of the native bridge. This information is available after a
113 // successful LoadNativeBridge() and before closing it, that is, as long as NativeBridgeAvailable()
114 // returns true. Returns 0 otherwise.
115 uint32_t NativeBridgeGetVersion();
116 
117 // Returns a signal handler that the bridge would like to be managed. Only valid for a native
118 // bridge supporting the version 2 interface. Will return null if the bridge does not support
119 // version 2, or if it doesn't have a signal handler it wants to be known.
120 NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal);
121 
122 // Returns whether we have seen a native bridge error. This could happen because the library
123 // was not found, rejected, could not be initialized and so on.
124 //
125 // This functionality is mainly for testing.
126 bool NativeBridgeError();
127 
128 // Returns whether a given string is acceptable as a native bridge library filename.
129 //
130 // This functionality is exposed mainly for testing.
131 bool NativeBridgeNameAcceptable(const char* native_bridge_library_filename);
132 
133 // Decrements the reference count on the dynamic library handler. If the reference count drops
134 // to zero then the dynamic library is unloaded. Returns 0 on success and non-zero on error.
135 int NativeBridgeUnloadLibrary(void* handle);
136 
137 // Get last error message of native bridge when fail to load library or search symbol.
138 // This is reflection of dlerror() for native bridge.
139 const char* NativeBridgeGetError();
140 
141 struct native_bridge_namespace_t;
142 
143 // True if native library paths are valid and is for an ABI that is supported by native bridge.
144 // Different from NativeBridgeIsSupported(), the *path* here must be a directory containing
145 // libraries of an ABI.
146 //
147 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
148 // Use NativeBridgeIsSupported() instead in non-namespace scenario.
149 bool NativeBridgeIsPathSupported(const char* path);
150 
151 // Create new namespace in which native libraries will be loaded.
152 // NativeBridge's peer of android_create_namespace() of dynamic linker.
153 //
154 // The libraries in the namespace are searched by folowing order:
155 // 1. ld_library_path (Think of this as namespace-local LD_LIBRARY_PATH)
156 // 2. In directories specified by DT_RUNPATH of the "needed by" binary.
157 // 3. deault_library_path (This of this as namespace-local default library path)
158 //
159 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
160 // Should not use in non-namespace scenario.
161 struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
162     const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
163     const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent_ns);
164 
165 // Creates a link which shares some libraries from one namespace to another.
166 // NativeBridge's peer of android_link_namespaces() of dynamic linker.
167 //
168 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
169 // Should not use in non-namespace scenario.
170 bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
171                                 struct native_bridge_namespace_t* to,
172                                 const char* shared_libs_sonames);
173 
174 // Load a shared library with namespace key that is supported by the native bridge.
175 // NativeBridge's peer of android_dlopen_ext() of dynamic linker, only supports namespace
176 // extension.
177 //
178 // Starting with v3, NativeBridge has two scenarios: with/without namespace.
179 // Use NativeBridgeLoadLibrary() instead in non-namespace scenario.
180 void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
181                                  struct native_bridge_namespace_t* ns);
182 
183 // Returns exported namespace by the name. This is a reflection of
184 // android_get_exported_namespace function. Introduced in v5.
185 struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name);
186 
187 // Native bridge interfaces to runtime.
188 struct NativeBridgeCallbacks {
189   // Version number of the interface.
190   uint32_t version;
191 
192   // Initialize native bridge. Native bridge's internal implementation must ensure MT safety and
193   // that the native bridge is initialized only once. Thus it is OK to call this interface for an
194   // already initialized native bridge.
195   //
196   // Parameters:
197   //   runtime_cbs [IN] the pointer to NativeBridgeRuntimeCallbacks.
198   // Returns:
199   //   true if initialization was successful.
200   bool (*initialize)(const struct NativeBridgeRuntimeCallbacks* runtime_cbs,
201                      const char* private_dir, const char* instruction_set);
202 
203   // Load a shared library that is supported by the native bridge.
204   //
205   // Parameters:
206   //   libpath [IN] path to the shared library
207   //   flag [IN] the stardard RTLD_XXX defined in bionic dlfcn.h
208   // Returns:
209   //   The opaque handle of the shared library if sucessful, otherwise NULL
210   //
211   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
212   // Use loadLibraryExt instead in namespace scenario.
213   void* (*loadLibrary)(const char* libpath, int flag);
214 
215   // Get a native bridge trampoline for specified native method. The trampoline has same
216   // signature as the native method.
217   //
218   // Parameters:
219   //   handle [IN] the handle returned from loadLibrary
220   //   shorty [IN] short descriptor of native method
221   //   len [IN] length of shorty
222   // Returns:
223   //   address of trampoline if successful, otherwise NULL
224   // Deprecated in v7
225   //   Starting with version 7 native bridge uses getTrampolineWithJNICallType
226   //   instead
227   void* (*getTrampoline)(void* handle, const char* name, const char* shorty, uint32_t len);
228 
229   // Check whether native library is valid and is for an ABI that is supported by native bridge.
230   //
231   // Parameters:
232   //   libpath [IN] path to the shared library
233   // Returns:
234   //   TRUE if library is supported by native bridge, FALSE otherwise
235   //
236   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
237   // Use isPathSupported instead in namespace scenario.
238   bool (*isSupported)(const char* libpath);
239 
240   // Provide environment values required by the app running with native bridge according to the
241   // instruction set.
242   //
243   // Parameters:
244   //   instruction_set [IN] the instruction set of the app
245   // Returns:
246   //   NULL if not supported by native bridge.
247   //   Otherwise, return all environment values to be set after fork.
248   const struct NativeBridgeRuntimeValues* (*getAppEnv)(const char* instruction_set);
249 
250   // Added callbacks in version 2.
251 
252   // Check whether the bridge is compatible with the given version. A bridge may decide not to be
253   // forwards- or backwards-compatible, and libnativebridge will then stop using it.
254   //
255   // Parameters:
256   //   bridge_version [IN] the version of libnativebridge.
257   // Returns:
258   //   true if the native bridge supports the given version of libnativebridge.
259   bool (*isCompatibleWith)(uint32_t bridge_version);
260 
261   // A callback to retrieve a native bridge's signal handler for the specified signal. The runtime
262   // will ensure that the signal handler is being called after the runtime's own handler, but before
263   // all chained handlers. The native bridge should not try to install the handler by itself, as
264   // that will potentially lead to cycles.
265   //
266   // Parameters:
267   //   signal [IN] the signal for which the handler is asked for. Currently, only SIGSEGV is
268   //                 supported by the runtime.
269   // Returns:
270   //   NULL if the native bridge doesn't use a handler or doesn't want it to be managed by the
271   //   runtime.
272   //   Otherwise, a pointer to the signal handler.
273   NativeBridgeSignalHandlerFn (*getSignalHandler)(int signal);
274 
275   // Added callbacks in version 3.
276 
277   // Decrements the reference count on the dynamic library handler. If the reference count drops
278   // to zero then the dynamic library is unloaded.
279   //
280   // Parameters:
281   //   handle [IN] the handler of a dynamic library.
282   //
283   // Returns:
284   //   0 on success, and nonzero on error.
285   int (*unloadLibrary)(void* handle);
286 
287   // Dump the last failure message of native bridge when fail to load library or search symbol.
288   //
289   // Parameters:
290   //
291   // Returns:
292   //   A string describing the most recent error that occurred when load library
293   //   or lookup symbol via native bridge.
294   const char* (*getError)();
295 
296   // Check whether library paths are supported by native bridge.
297   //
298   // Parameters:
299   //   library_path [IN] search paths for native libraries (directories separated by ':')
300   // Returns:
301   //   TRUE if libraries within search paths are supported by native bridge, FALSE otherwise
302   //
303   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
304   // Use isSupported instead in non-namespace scenario.
305   bool (*isPathSupported)(const char* library_path);
306 
307   // No longer used.
308   bool (*unused_initAnonymousNamespace)(const char*, const char*);
309 
310   // Create new namespace in which native libraries will be loaded.
311   // NativeBridge's peer of android_create_namespace() of dynamic linker.
312   //
313   // Parameters:
314   //   name [IN] the name of the namespace.
315   //   ld_library_path [IN] the first set of library search paths of the namespace.
316   //   default_library_path [IN] the second set of library search path of the namespace.
317   //   type [IN] the attribute of the namespace.
318   //   permitted_when_isolated_path [IN] the permitted path for isolated namespace(if it is).
319   //   parent_ns [IN] the pointer of the parent namespace to be inherited from.
320   // Returns:
321   //   native_bridge_namespace_t* for created namespace or nullptr in the case of error.
322   //
323   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
324   // Should not use in non-namespace scenario.
325   struct native_bridge_namespace_t* (*createNamespace)(const char* name,
326                                                        const char* ld_library_path,
327                                                        const char* default_library_path,
328                                                        uint64_t type,
329                                                        const char* permitted_when_isolated_path,
330                                                        struct native_bridge_namespace_t* parent_ns);
331 
332   // Creates a link which shares some libraries from one namespace to another.
333   // NativeBridge's peer of android_link_namespaces() of dynamic linker.
334   //
335   // Parameters:
336   //   from [IN] the namespace where libraries are accessed.
337   //   to [IN] the namespace where libraries are loaded.
338   //   shared_libs_sonames [IN] the libraries to be shared.
339   //
340   // Returns:
341   //   Whether successed or not.
342   //
343   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
344   // Should not use in non-namespace scenario.
345   bool (*linkNamespaces)(struct native_bridge_namespace_t* from,
346                          struct native_bridge_namespace_t* to, const char* shared_libs_sonames);
347 
348   // Load a shared library within a namespace.
349   // NativeBridge's peer of android_dlopen_ext() of dynamic linker, only supports namespace
350   // extension.
351   //
352   // Parameters:
353   //   libpath [IN] path to the shared library
354   //   flag [IN] the stardard RTLD_XXX defined in bionic dlfcn.h
355   //   ns [IN] the pointer of the namespace in which the library should be loaded.
356   // Returns:
357   //   The opaque handle of the shared library if sucessful, otherwise NULL
358   //
359   // Starting with v3, NativeBridge has two scenarios: with/without namespace.
360   // Use loadLibrary instead in non-namespace scenario.
361   void* (*loadLibraryExt)(const char* libpath, int flag, struct native_bridge_namespace_t* ns);
362 
363   // Get native bridge version of vendor namespace.
364   // The vendor namespace is the namespace used to load vendor public libraries.
365   // With O release this namespace can be different from the default namespace.
366   // For the devices without enable vendor namespaces this function should return null
367   //
368   // Returns:
369   //   vendor namespace or null if it was not set up for the device
370   //
371   // Starting with v5 (Android Q) this function is no longer used.
372   // Use getExportedNamespace() below.
373   struct native_bridge_namespace_t* (*getVendorNamespace)();
374 
375   // Get native bridge version of exported namespace. Peer of
376   // android_get_exported_namespace(const char*) function.
377   //
378   // Returns:
379   //   exported namespace or null if it was not set up for the device
380   struct native_bridge_namespace_t* (*getExportedNamespace)(const char* name);
381 
382   // If native bridge is used in app-zygote (in doPreload()) this callback is
383   // required to clean-up the environment before the fork (see b/146904103).
384   void (*preZygoteFork)();
385 
386   // This replaces previous getTrampoline call starting with version 7 of the
387   // interface.
388   //
389   // Get a native bridge trampoline for specified native method. The trampoline
390   // has same signature as the native method.
391   //
392   // Parameters:
393   //   handle [IN] the handle returned from loadLibrary
394   //   shorty [IN] short descriptor of native method
395   //   len [IN] length of shorty
396   //   jni_call_type [IN] the type of JNI call
397   // Returns:
398   //   address of trampoline if successful, otherwise NULL
399   void* (*getTrampolineWithJNICallType)(void* handle,
400                                         const char* name,
401                                         const char* shorty,
402                                         uint32_t len,
403                                         enum JNICallType jni_call_type);
404 
405   // Get a native bridge trampoline for specified native method implementation pointer.
406   //
407   // Parameters:
408   //   method [IN] pointer to method implementation (usually registered via call to
409   //   RegisterNatives).
410   //   shorty [IN] short descriptor of native method
411   //   len [IN] length of shorty
412   //   jni_call_type [IN] the type of JNI call
413   // Returns:
414   //   address of trampoline if successful, otherwise NULL
415   void* (*getTrampolineForFunctionPointer)(const void* method,
416                                            const char* shorty,
417                                            uint32_t len,
418                                            enum JNICallType jni_call_type);
419 
420   // Check if the method pointer belongs to native_bridge address space.
421   //
422   // Parameters:
423   //   method [IN] pointer to a method implementation.
424   //
425   // Returns:
426   //   true if the method is in native bridge implementation executable address
427   //   space or in other words needs a trampoline to be able to run with native bridge.
428   //
429   // Introduced in: version 8
430   bool (*isNativeBridgeFunctionPointer)(const void* method);
431 };
432 
433 // Runtime interfaces to native bridge.
434 struct NativeBridgeRuntimeCallbacks {
435   // Get shorty of a Java method. The shorty is supposed to be persistent in memory.
436   //
437   // Parameters:
438   //   env [IN] pointer to JNIenv.
439   //   mid [IN] Java methodID.
440   // Returns:
441   //   short descriptor for method.
442   const char* (*getMethodShorty)(JNIEnv* env, jmethodID mid);
443 
444   // Get number of native methods for specified class.
445   //
446   // Parameters:
447   //   env [IN] pointer to JNIenv.
448   //   clazz [IN] Java class object.
449   // Returns:
450   //   number of native methods.
451   uint32_t (*getNativeMethodCount)(JNIEnv* env, jclass clazz);
452 
453   // Get at most 'method_count' native methods for specified class 'clazz'. Results are outputed
454   // via 'methods' [OUT]. The signature pointer in JNINativeMethod is reused as the method shorty.
455   //
456   // Parameters:
457   //   env [IN] pointer to JNIenv.
458   //   clazz [IN] Java class object.
459   //   methods [OUT] array of method with the name, shorty, and fnPtr.
460   //   method_count [IN] max number of elements in methods.
461   // Returns:
462   //   number of method it actually wrote to methods.
463   uint32_t (*getNativeMethods)(JNIEnv* env, jclass clazz, JNINativeMethod* methods,
464                                uint32_t method_count);
465 };
466 
467 #ifdef __cplusplus
468 }  // extern "C"
469 }  // namespace android
470 #endif  // __cplusplus
471 
472 #endif  // ART_LIBNATIVEBRIDGE_INCLUDE_NATIVEBRIDGE_NATIVE_BRIDGE_H_
473