Skip to content

Commit fae5de6

Browse files
committed
fix: keep strings intact across JNI and bind both AudioResampler initializers
Native strings went back through NewStringUTF, which takes Modified UTF-8, so emoji and embedded NULs came back changed, and empty strings became null. Convert UTF-8 to UTF-16 properly and keep "" as "", mapping to null only where WebRTC encodes an absent value as empty or unset. The checked-in header lacked the long JNI names of the overloaded AudioResampler.initialize, so initialize(int, int, int) had C++ linkage and Java bound it to the parameterless function. CI now compares the JNI names javac generates with the declared and defined ones.
1 parent cdcbb34 commit fae5de6

14 files changed

Lines changed: 526 additions & 51 deletions

File tree

‎.github/scripts/check-jni-names.sh‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
#!/usr/bin/env bash
2+
#
3+
# Checks that the JNI functions of the native code are the ones the Java
4+
# classes bind to. For every module with native methods it compares three sets
5+
# of JNI names:
6+
#
7+
# expected what javac -h generates for the native methods of the Java code,
8+
# test classes included (fault injection lives in the tests)
9+
# declared what the checked-in headers under include/ declare
10+
# defined what the sources under src/ define with JNIEXPORT
11+
#
12+
# All three must be equal. An overloaded native method binds to a long name
13+
# (initialize__ and initialize__III); a stale short name next to it takes the
14+
# binding of both overloads. A definition that no header declares has C++
15+
# linkage, so it is exported mangled and the JVM never finds it.
16+
#
17+
# Usage: check-jni-names.sh [repository root]
18+
# Needs a JDK (javac) on the PATH.
19+
20+
set -euo pipefail
21+
22+
ROOT="$(cd "${1:-$(dirname "$0")/../..}" && pwd)"
23+
WORK="$(mktemp -d)"
24+
trap 'rm -rf "$WORK"' EXIT
25+
26+
failed=0
27+
28+
# Prints the JNI names on the JNIEXPORT lines of the given files, sorted.
29+
jni_names() {
30+
grep -h 'JNIEXPORT' "$@" | grep -o 'Java_[A-Za-z0-9_]*' | sort -u || true
31+
}
32+
33+
# Compiles a module's Java sources, generating its JNI headers into $WORK/<name>.
34+
# $1 name, $2 source dir, remaining: extra javac options.
35+
generate() {
36+
local name="$1" src="$2"
37+
shift 2
38+
39+
find "$src" -name '*.java' > "$WORK/$name-sources.txt"
40+
41+
if ! javac --release 11 -nowarn -d "$WORK/$name-classes" -h "$WORK/$name-headers" "$@" \
42+
@"$WORK/$name-sources.txt" > "$WORK/$name-javac.log" 2>&1; then
43+
cat "$WORK/$name-javac.log"
44+
exit 1
45+
fi
46+
}
47+
48+
# Generates the JNI headers of the test classes that declare native methods,
49+
# compiled against the module's classes. $1 name, $2 test source dir,
50+
# $3 class path.
51+
generate_tests() {
52+
local name="$1" src="$2" classpath="$3"
53+
54+
[ -d "$src" ] || return 0
55+
56+
grep -rlE '^\s*((public|protected|private|static|final|synchronized)\s+)*native\s+[][A-Za-z0-9_.<>, ]+\s+[A-Za-z0-9_]+\s*\(' \
57+
--include='*.java' "$src" > "$WORK/$name-test-sources.txt" || true
58+
59+
[ -s "$WORK/$name-test-sources.txt" ] || return 0
60+
61+
if ! javac --release 11 -nowarn -cp "$classpath" -d "$WORK/$name-test-classes" -h "$WORK/$name-headers" \
62+
@"$WORK/$name-test-sources.txt" > "$WORK/$name-test-javac.log" 2>&1; then
63+
cat "$WORK/$name-test-javac.log"
64+
exit 1
65+
fi
66+
}
67+
68+
# Prints the names of the first list that are missing from the second.
69+
# $1 title, $2 first, $3 second.
70+
report() {
71+
local missing
72+
missing="$(comm -23 "$2" "$3")"
73+
74+
if [ -n "$missing" ]; then
75+
echo " $1:"
76+
echo "$missing" | sed 's/^/ /'
77+
failed=1
78+
fi
79+
}
80+
81+
# $1 name, $2 native source root (holding include/ and src/).
82+
check() {
83+
local name="$1" cpp="$2"
84+
local expected="$WORK/$name-expected.txt"
85+
local declared="$WORK/$name-declared.txt"
86+
local defined="$WORK/$name-defined.txt"
87+
88+
jni_names "$WORK/$name-headers"/*.h > "$expected"
89+
find "$cpp/include" -name '*.h' -print0 | xargs -0 grep -l 'JNIEXPORT' | xargs -r cat | jni_names /dev/stdin > "$declared"
90+
find "$cpp/src" -name '*.cpp' -print0 | xargs -0 grep -l 'JNIEXPORT' | xargs -r cat | jni_names /dev/stdin > "$defined"
91+
92+
echo "$name: $(wc -l < "$expected") native methods"
93+
94+
report "native methods without a declaration in include/" "$expected" "$declared"
95+
report "declarations of no native method (stale, or a short name of an overload)" "$declared" "$expected"
96+
report "native methods without a definition in src/" "$expected" "$defined"
97+
report "definitions without a declaration (C++ linkage, unreachable from Java)" "$defined" "$declared"
98+
}
99+
100+
generate webrtc "$ROOT/webrtc/src/main/java"
101+
generate_tests webrtc "$ROOT/webrtc/src/test/java" "$WORK/webrtc-classes"
102+
check webrtc "$ROOT/webrtc-jni/src/main/cpp"
103+
104+
generate webrtc-media "$ROOT/webrtc-media/src/main/java" --module-path "$WORK/webrtc-classes"
105+
generate_tests webrtc-media "$ROOT/webrtc-media/src/test/java" "$WORK/webrtc-classes:$WORK/webrtc-media-classes"
106+
check webrtc-media "$ROOT/webrtc-media/src/main/cpp"
107+
108+
if [ "$failed" -ne 0 ]; then
109+
echo "The JNI names of the native code do not match the Java classes." >&2
110+
exit 1
111+
fi

‎.github/workflows/build.yml‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,25 @@ concurrency:
3737
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
3838

3939
jobs:
40+
# The JNI functions must carry the names javac -h gives the native methods.
41+
# A wrong one still compiles and links, and the JVM then binds a method to
42+
# the wrong function or to none, so no native build would notice.
43+
jni-names:
44+
name: Check JNI names
45+
runs-on: ubuntu-22.04
46+
steps:
47+
- name: Checkout code
48+
uses: actions/checkout@v7
49+
50+
- name: Set up JDK 17
51+
uses: actions/setup-java@v6
52+
with:
53+
java-version: '17'
54+
distribution: 'temurin'
55+
56+
- name: Compare the JNI names with the native methods
57+
run: .github/scripts/check-jni-names.sh
58+
4059
platforms:
4160
uses: ./.github/workflows/platforms.yml
4261
with:

‎webrtc-jni/src/main/cpp/dependencies/jni-voithos/include/JavaString.h‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
#include <jni.h>
1515
#include <string>
16+
#include <vector>
1617

1718
namespace jni
1819
{
@@ -21,13 +22,18 @@ namespace jni
2122
public:
2223
explicit JavaString(JNIEnv * env);
2324

25+
// UTF-16 to UTF-8; null becomes "".
2426
static std::string toNative(JNIEnv * env, const JavaRef<jstring> & jstr);
27+
// UTF-8 to UTF-16, never null: "" stays "", U+0000 and characters
28+
// beyond the BMP survive.
2529
static JavaLocalRef<jstring> toJava(JNIEnv * env, const std::string & str);
30+
// For values that WebRTC leaves empty when they are absent and that
31+
// Java reports as null.
32+
static JavaLocalRef<jstring> toJavaOrNull(JNIEnv * env, const std::string & str);
2633
static JavaLocalRef<jobjectArray> createArray(JNIEnv * env, const std::vector<std::string> & vector);
2734

2835
private:
2936
jclass cls;
30-
jmethodID getBytes;
3137
};
3238
}
3339

‎webrtc-jni/src/main/cpp/dependencies/jni-voithos/src/JavaString.cpp‎

Lines changed: 162 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,154 @@
1010
#include "JavaString.h"
1111
#include "JavaUtils.h"
1212

13+
#include <vector>
14+
1315
namespace jni
1416
{
17+
namespace
18+
{
19+
constexpr jchar kReplacementChar = 0xFFFD;
20+
21+
bool IsContinuation(unsigned char byte, unsigned char low = 0x80, unsigned char high = 0xBF)
22+
{
23+
return byte >= low && byte <= high;
24+
}
25+
26+
void AppendCodePoint(std::vector<jchar> & out, char32_t cp)
27+
{
28+
if (cp < 0x10000) {
29+
out.push_back(static_cast<jchar>(cp));
30+
}
31+
else {
32+
cp -= 0x10000;
33+
out.push_back(static_cast<jchar>(0xD800 + (cp >> 10)));
34+
out.push_back(static_cast<jchar>(0xDC00 + (cp & 0x3FF)));
35+
}
36+
}
37+
38+
// Standard UTF-8 to UTF-16. JNI's NewStringUTF takes Modified UTF-8,
39+
// which encodes U+0000 and supplementary characters differently and
40+
// mangles what WebRTC hands out. Every ill-formed sequence becomes one
41+
// U+FFFD per maximal subpart (Unicode 3.9, Table 3-7), as Java's own
42+
// UTF-8 decoder does.
43+
std::vector<jchar> DecodeUtf8(const std::string & str)
44+
{
45+
const auto * bytes = reinterpret_cast<const unsigned char *>(str.data());
46+
const size_t length = str.size();
47+
48+
std::vector<jchar> out;
49+
out.reserve(length);
50+
51+
size_t i = 0;
52+
53+
while (i < length) {
54+
const unsigned char lead = bytes[i];
55+
56+
if (lead < 0x80) {
57+
out.push_back(lead);
58+
i++;
59+
continue;
60+
}
61+
62+
size_t count;
63+
char32_t cp;
64+
unsigned char low = 0x80;
65+
unsigned char high = 0xBF;
66+
67+
if (lead >= 0xC2 && lead <= 0xDF) {
68+
count = 1;
69+
cp = lead & 0x1F;
70+
}
71+
else if (lead >= 0xE0 && lead <= 0xEF) {
72+
count = 2;
73+
cp = lead & 0x0F;
74+
low = lead == 0xE0 ? 0xA0 : 0x80;
75+
high = lead == 0xED ? 0x9F : 0xBF; // No surrogates.
76+
}
77+
else if (lead >= 0xF0 && lead <= 0xF4) {
78+
count = 3;
79+
cp = lead & 0x07;
80+
low = lead == 0xF0 ? 0x90 : 0x80;
81+
high = lead == 0xF4 ? 0x8F : 0xBF; // Nothing above U+10FFFF.
82+
}
83+
else {
84+
out.push_back(kReplacementChar);
85+
i++;
86+
continue;
87+
}
88+
89+
size_t consumed = 1;
90+
91+
while (consumed <= count && i + consumed < length) {
92+
const unsigned char next = bytes[i + consumed];
93+
94+
// Only the first continuation byte has a narrowed range.
95+
if (consumed == 1 ? !IsContinuation(next, low, high) : !IsContinuation(next)) {
96+
break;
97+
}
98+
99+
cp = (cp << 6) | (next & 0x3F);
100+
consumed++;
101+
}
102+
103+
if (consumed == count + 1) {
104+
AppendCodePoint(out, cp);
105+
}
106+
else {
107+
out.push_back(kReplacementChar);
108+
}
109+
110+
i += consumed;
111+
}
112+
113+
return out;
114+
}
115+
116+
// Standard UTF-16 to UTF-8. An unpaired surrogate becomes '?', as with
117+
// String.getBytes(UTF_8).
118+
std::string EncodeUtf8(const std::vector<jchar> & chars)
119+
{
120+
std::string out;
121+
out.reserve(chars.size());
122+
123+
for (size_t i = 0; i < chars.size(); i++) {
124+
char32_t cp = chars[i];
125+
126+
if (cp >= 0xD800 && cp <= 0xDBFF && i + 1 < chars.size() && chars[i + 1] >= 0xDC00 && chars[i + 1] <= 0xDFFF) {
127+
cp = 0x10000 + ((cp - 0xD800) << 10) + (chars[i + 1] - 0xDC00);
128+
i++;
129+
}
130+
else if (cp >= 0xD800 && cp <= 0xDFFF) {
131+
cp = '?';
132+
}
133+
134+
if (cp < 0x80) {
135+
out.push_back(static_cast<char>(cp));
136+
}
137+
else if (cp < 0x800) {
138+
out.push_back(static_cast<char>(0xC0 | (cp >> 6)));
139+
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
140+
}
141+
else if (cp < 0x10000) {
142+
out.push_back(static_cast<char>(0xE0 | (cp >> 12)));
143+
out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
144+
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
145+
}
146+
else {
147+
out.push_back(static_cast<char>(0xF0 | (cp >> 18)));
148+
out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
149+
out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
150+
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
151+
}
152+
}
153+
154+
return out;
155+
}
156+
}
157+
15158
JavaString::JavaString(JNIEnv * env)
16159
{
17160
cls = FindClass(env, "java/lang/String");
18-
19-
getBytes = GetMethod(env, cls, "getBytes", "(Ljava/lang/String;)[B");
20161
}
21162

22163
std::string JavaString::toNative(JNIEnv * env, const JavaRef<jstring> & jstr)
@@ -25,25 +166,35 @@ namespace jni
25166
return "";
26167
}
27168

28-
const auto strClass = JavaClasses::get<JavaString>(env);
29-
30-
jbyteArray stringBytes = static_cast<jbyteArray>(env->CallObjectMethod(jstr, strClass->getBytes, env->NewStringUTF("UTF-8")));
31-
jsize length = env->GetArrayLength(stringBytes);
169+
const jsize length = env->GetStringLength(jstr);
32170

33-
std::string str(length, '\0');
171+
std::vector<jchar> chars(static_cast<size_t>(length));
34172

35-
env->GetByteArrayRegion(stringBytes, 0, length, reinterpret_cast<jbyte *>(&str[0]));
173+
if (length > 0) {
174+
env->GetStringRegion(jstr, 0, length, chars.data());
175+
}
36176

37-
return str;
177+
return EncodeUtf8(chars);
38178
}
39179

40180
JavaLocalRef<jstring> JavaString::toJava(JNIEnv * env, const std::string & str)
181+
{
182+
static const jchar empty = 0;
183+
184+
const std::vector<jchar> chars = DecodeUtf8(str);
185+
const jchar * data = chars.empty() ? &empty : chars.data();
186+
187+
// A null result means an OutOfMemoryError is pending.
188+
return JavaLocalRef<jstring>(env, env->NewString(data, static_cast<jsize>(chars.size())));
189+
}
190+
191+
JavaLocalRef<jstring> JavaString::toJavaOrNull(JNIEnv * env, const std::string & str)
41192
{
42193
if (str.empty()) {
43194
return nullptr;
44195
}
45196

46-
return JavaLocalRef<jstring>(env, env->NewStringUTF(str.c_str()));
197+
return toJava(env, str);
47198
}
48199

49200
JavaLocalRef<jobjectArray> JavaString::createArray(JNIEnv * env, const std::vector<std::string> & vector)
@@ -52,4 +203,4 @@ namespace jni
52203

53204
return JavaArray::createObjectArray(env, vector, javaClass->cls, &toJava);
54205
}
55-
}
206+
}

‎webrtc-jni/src/main/cpp/include/JNI_AudioResampler.h‎

Lines changed: 10 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)