@@ -47,27 +47,39 @@ JNIEXPORT jstring JNICALL Java_jssc_SerialNativeInterface_getNativeLibraryVersio
4747 */
4848JNIEXPORT jlong JNICALL Java_jssc_SerialNativeInterface_openPort (JNIEnv *env, jobject, jstring portName, jboolean){
4949 char prefix[] = " \\\\ .\\ " ;
50- const char * port = env->GetStringUTFChars (portName, JNI_FALSE );
50+ const char * port = NULL ;
51+ HANDLE hComm = NULL ;
52+ jlong retval = 0 ;
53+
54+ port = env->GetStringUTFChars (portName, NULL );
55+ if ( !port ){
56+ if ( !env->ExceptionCheck () ){
57+ /* Can happen if the given input is `NULL`. So let our caller know. */
58+ jclass exClz = env->FindClass (" java/lang/IllegalArgumentException" );
59+ if ( exClz ) env->ThrowNew (exClz, " portName" );
60+ }
61+ goto resolveWithRetval;
62+ }
5163
5264 // since 2.1.0 -> string concat fix
5365 char portFullName[MAX_PORT_NAME_STR_LEN ];
5466
5567 if (strlen (prefix) + strlen (port) + 1 > sizeof (portFullName)){
56- return (jlong)((HANDLE )jssc_SerialNativeInterface_ERR_PORT_NOT_FOUND);
68+ retval = (jlong)((HANDLE )jssc_SerialNativeInterface_ERR_PORT_NOT_FOUND);
69+ goto resolveWithRetval;
5770 }
5871
5972 strcpy_s (portFullName, prefix);
6073 strcat_s (portFullName, port);
6174 // <- since 2.1.0
6275
63- HANDLE hComm = CreateFile (portFullName,
76+ hComm = CreateFile (portFullName,
6477 GENERIC_READ | GENERIC_WRITE ,
6578 0 ,
6679 0 ,
6780 OPEN_EXISTING ,
6881 FILE_FLAG_OVERLAPPED ,
6982 0 );
70- env->ReleaseStringUTFChars (portName, port);
7183
7284 // since 2.3.0 ->
7385 if (hComm != INVALID_HANDLE_VALUE ){
@@ -88,7 +100,12 @@ JNIEXPORT jlong JNICALL Java_jssc_SerialNativeInterface_openPort(JNIEnv *env, jo
88100 }
89101 }
90102 // <- since 2.3.0
91- return (jlong)hComm;// since 2.4.0 changed to jlong
103+ retval = (jlong)hComm;// since 2.4.0 changed to jlong
104+ resolveWithRetval:
105+ if ( port ){
106+ env->ReleaseStringUTFChars (portName, port);
107+ }
108+ return retval;
92109}
93110
94111/*
@@ -298,7 +315,7 @@ JNIEXPORT jbyteArray JNICALL Java_jssc_SerialNativeInterface_readBytes
298315 lpBuffer = (jbyte*)malloc (byteCount*sizeof *lpBuffer);
299316 if ( !lpBuffer ){
300317 char emsg[32 ]; emsg[0 ] = ' \0 ' ;
301- snprintf (emsg, sizeof emsg, " malloc(%d ) failed" , byteCount*sizeof *lpBuffer);
318+ snprintf (emsg, sizeof emsg, " malloc(%llu ) failed" , ( long long unsigned ) byteCount*sizeof *lpBuffer);
302319 jclass exClz = env->FindClass (" java/lang/RuntimeException" );
303320 if ( exClz ) env->ThrowNew (exClz, emsg);
304321 returnArray = NULL ; goto Finally;
0 commit comments