From d5966b3b84206472bd4f800aab7b7476883324d8 Mon Sep 17 00:00:00 2001 From: "Andreas Fankhauser hiddenalpha.ch" <23085769+hiddenalpha@users.noreply.github.com> Date: Fri, 22 Nov 2024 03:54:30 +0100 Subject: [PATCH] Handle some IllegalArgument cases in readBytes The 2nd error covered here potentially could explain cases like https://github.com/java-native/jssc/issues/122 or related. Example: Passed-in 'byteCount' is either far too large or even a negative value which could trigger undesired behavior when used to allocate an array. --- src/main/cpp/_nix_based/jssc.cpp | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/main/cpp/_nix_based/jssc.cpp b/src/main/cpp/_nix_based/jssc.cpp index 87fb1a753..07969fe1f 100644 --- a/src/main/cpp/_nix_based/jssc.cpp +++ b/src/main/cpp/_nix_based/jssc.cpp @@ -657,10 +657,31 @@ JNIEXPORT jbyteArray JNICALL Java_jssc_SerialNativeInterface_readBytes (JNIEnv *env, jobject, jlong portHandle, jint byteCount){ int err; - jbyte *lpBuffer = new jbyte[byteCount]; + jbyte *lpBuffer = NULL; jbyteArray returnArray = NULL; int byteRemains = byteCount; + if( byteCount < 0 ){ + char emsg[32]; emsg[0] = '\0'; + snprintf(emsg, sizeof emsg, "new byte[%d]", byteCount); + jclass exClz = env->FindClass("java/lang/IllegalArgumentException"); + if( exClz != NULL ) env->ThrowNew(exClz, emsg); + returnArray = NULL; goto Finally; + } + + try{ + lpBuffer = new jbyte[byteCount]; + }catch( const std::bad_alloc& ex ){ + lpBuffer = NULL; + } + if( lpBuffer == NULL ){ + char emsg[32]; emsg[0] = '\0'; + snprintf(emsg, sizeof emsg, "new byte[%d]", byteCount); + jclass exClz = env->FindClass("java/lang/OutOfMemoryError"); + if( exClz != NULL ) env->ThrowNew(exClz, emsg); + returnArray = NULL; goto Finally; + } + while(byteRemains > 0) { int result = 0; @@ -707,7 +728,7 @@ JNIEXPORT jbyteArray JNICALL Java_jssc_SerialNativeInterface_readBytes assert(env->ExceptionCheck() == JNI_FALSE); Finally: - delete[] lpBuffer; + if( lpBuffer != NULL ) delete[] lpBuffer; return returnArray; }