• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2023 The Chromium Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Logic related to proxying calls through GEN_JNI.java."""
5
6import base64
7import hashlib
8
9import common
10import java_types
11
12# 'Proxy' native methods are declared in an @NativeMethods interface without
13# a native qualifier and indicate that the JNI annotation processor should
14# generate code to link between the equivalent native method as if it were
15# declared statically.
16
17_MAX_CHARS_FOR_HASHED_NATIVE_METHODS = 8
18
19
20def get_gen_jni_class(*, short=False, name_prefix=None, package_prefix=None):
21  """Returns the JavaClass for GEN_JNI."""
22  package = 'J' if short else 'org/jni_zero'
23  name_prefix = name_prefix + '_' if name_prefix else ''
24  name = name_prefix + ('N' if short else 'GEN_JNI')
25
26  return java_types.JavaClass(f'{package}/{name}').make_prefixed(package_prefix)
27
28
29def _create_hashed_method_name(non_hashed_name, is_test_only):
30  md5 = hashlib.md5(non_hashed_name.encode('utf8')).digest()
31  hash_b64 = base64.b64encode(md5, altchars=b'$_').decode('utf-8')
32
33  long_hash = ('M' + hash_b64).rstrip('=')
34  hashed_name = long_hash[:_MAX_CHARS_FOR_HASHED_NATIVE_METHODS]
35
36  # If the method is a test-only method, we don't care about saving size on
37  # the method name, since it shouldn't show up in the binary. Additionally,
38  # if we just hash the name, our checkers which enforce that we have no
39  # "ForTesting" methods by checking for the suffix "ForTesting" will miss
40  # these. We could preserve the name entirely and not hash anything, but
41  # that risks collisions. So, instead, we just append "ForTesting" to any
42  # test-only hashes, to ensure we catch any test-only methods that
43  # shouldn't be in our final binary.
44  if is_test_only:
45    return hashed_name + '_ForTesting'
46  return hashed_name
47
48
49def create_method_names(java_class, method_name, is_test_only):
50  """Returns the method name used in GEN_JNI (both hashed an non-hashed)."""
51  proxy_name = common.escape_class_name(
52      f'{java_class.full_name_with_slashes}/{method_name}')
53  hashed_proxy_name = _create_hashed_method_name(proxy_name, is_test_only)
54  return proxy_name, hashed_proxy_name
55