Skip to content

Commit

Permalink
Handle some IllegalArgument cases in readBytes
Browse files Browse the repository at this point in the history
The 2nd error covered here potentially could explain cases like

java-native#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.
  • Loading branch information
hiddenalpha committed Nov 22, 2024
1 parent 8dd99a4 commit d5966b3
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/main/cpp/_nix_based/jssc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit d5966b3

Please sign in to comment.