Catch double-exit crash with IllegalStatException

This commit is contained in:
Klaus Reimer 2013-04-17 21:10:54 +02:00
parent fc4f7ced60
commit 2af4393d2e
3 changed files with 29 additions and 4 deletions

View File

@ -25,6 +25,8 @@
static JavaVM *jvm;
static int defaultContextInitialized = 0;
/**
* Version getVersion()
*/
@ -46,7 +48,13 @@ JNIEXPORT jint JNICALL METHOD_NAME(LibUsb, init)
{
if (!context)
{
return libusb_init(NULL);
if (defaultContextInitialized)
{
return illegalState(env, "Default context already initialized");
}
int result = libusb_init(NULL);
if (!result) defaultContextInitialized = 1;
return result;
}
else
{
@ -67,8 +75,17 @@ JNIEXPORT void JNICALL METHOD_NAME(LibUsb, exit)
{
struct libusb_context *ctx = unwrapContext(env, context);
if (!ctx && context) return;
if (!context && !defaultContextInitialized)
{
illegalState(env, "Default context not initialized");
return;
}
libusb_exit(ctx);
resetContext(env, context);
if (context)
resetContext(env, context);
else
defaultContextInitialized = 0;
}
/**

View File

@ -176,8 +176,16 @@ public class LibUSBTest
assertEquals(LibUsb.SUCCESS, LibUsb.init(null));
LibUsb.exit(null);
// Double-exit without a context should work
LibUsb.exit(null);
try
{
// Double-exit should throw exception
LibUsb.exit(null);
fail("Double-exit should throw IllegalStateException");
}
catch (IllegalStateException e)
{
// Expected behavior
}
}
/**