Skip to content

Commit f1aae67

Browse files
committed
IO: Fix crash when I2C.read() was called without prior write()
1 parent 6073d7b commit f1aae67

File tree

1 file changed

+18
-14
lines changed
  • java/libraries/io/src/native

1 file changed

+18
-14
lines changed

java/libraries/io/src/native/impl.c

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -304,29 +304,33 @@ JNIEXPORT jint JNICALL Java_processing_io_NativeInterface_transferI2c
304304
jbyte *out, *in;
305305

306306
packets.msgs = msgs;
307-
308-
msgs[0].addr = slave;
309-
msgs[0].flags = 0;
310-
msgs[0].len = (*env)->GetArrayLength(env, _out);
311-
out = (*env)->GetByteArrayElements(env, _out, NULL);
312-
msgs[0].buf = out;
307+
packets.nmsgs = 0;
308+
309+
if (_out != NULL) {
310+
msgs[packets.nmsgs].addr = slave;
311+
msgs[packets.nmsgs].flags = 0;
312+
msgs[packets.nmsgs].len = (*env)->GetArrayLength(env, _out);
313+
out = (*env)->GetByteArrayElements(env, _out, NULL);
314+
msgs[packets.nmsgs].buf = out;
315+
packets.nmsgs++;
316+
}
313317
if (_in != NULL) {
318+
msgs[packets.nmsgs].addr = slave;
319+
msgs[packets.nmsgs].flags = I2C_M_RD; // I2C_M_RECV_LEN is not supported
320+
msgs[packets.nmsgs].len = (*env)->GetArrayLength(env, _in);
314321
in = (*env)->GetByteArrayElements(env, _in, NULL);
315-
msgs[1].addr = slave;
316-
msgs[1].flags = I2C_M_RD; // I2C_M_RECV_LEN is not supported
317-
msgs[1].len = (*env)->GetArrayLength(env, _in);
318-
msgs[1].buf = in;
319-
packets.nmsgs = 2;
320-
} else {
321-
packets.nmsgs = 1;
322+
msgs[packets.nmsgs].buf = in;
323+
packets.nmsgs++;
322324
}
323325

324326
int ret = ioctl(handle, I2C_RDWR, &packets);
325327
if (ret < 0) {
326328
ret = -errno;
327329
}
328330

329-
(*env)->ReleaseByteArrayElements(env, _out, out, JNI_ABORT);
331+
if (_out != NULL) {
332+
(*env)->ReleaseByteArrayElements(env, _out, out, JNI_ABORT);
333+
}
330334
if (_in != NULL) {
331335
(*env)->ReleaseByteArrayElements(env, _in, in, 0);
332336
}

0 commit comments

Comments
 (0)