-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
dispatch.c
3676 lines (3425 loc) · 120 KB
/
dispatch.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* @(#)dispatch.c 1.9 98/03/22
*
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
* Copyright (c) 2007-2013 Timothy Wall. All Rights Reserved.
* Copyright (c) 2007 Wayne Meissner. All Rights Reserved.
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
#include "dispatch.h"
#include <string.h>
#include <stdlib.h>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <psapi.h>
#define STRTYPE wchar_t*
#define NAME2CSTR(ENV,JSTR) newWideCString(ENV,JSTR)
#ifdef _WIN32_WCE
#include <tlhelp32.h>
#define DEFAULT_LOAD_OPTS 0 /* altered search path unsupported on CE */
#undef GetProcAddress
#define GetProcAddress GetProcAddressA
#else
/* See http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx:
* "Note that the standard search strategy and the alternate search strategy
* specified by LoadLibraryEx with LOAD_WITH_ALTERED_SEARCH_PATH differ in
* just one way: The standard search begins in the calling application's
* directory, and the alternate search begins in the directory of the
* executable module that LoadLibraryEx is loading."
*/
#define DEFAULT_LOAD_OPTS LOAD_WITH_ALTERED_SEARCH_PATH
#endif
#define LOAD_LIBRARY(NAME,OPTS) (NAME ? LoadLibraryExW(NAME, NULL, OPTS) : GetModuleHandleW(NULL))
#define LOAD_ERROR() w32_format_error(GetLastError())
#define STR_ERROR(CODE) w32_format_error(CODE)
#define FREE_LIBRARY(HANDLE) (((HANDLE)==GetModuleHandleW(NULL) || FreeLibrary(HANDLE))?0:-1)
#define FIND_ENTRY(HANDLE, NAME) w32_find_entry(env, HANDLE, NAME)
#else
#include <dlfcn.h>
#include <errno.h>
#include <assert.h>
#define STRTYPE char*
#ifdef USE_DEFAULT_LIBNAME_ENCODING
#define NAME2CSTR(ENV,JSTR) newCString(ENV,JSTR)
#else
#define NAME2CSTR(ENV,JSTR) newCStringUTF8(ENV,JSTR)
#endif
#define DEFAULT_LOAD_OPTS (RTLD_LAZY|RTLD_GLOBAL)
#define LOAD_LIBRARY(NAME,OPTS) dlopen(NAME, OPTS)
static inline char * LOAD_ERROR() {
const char* message = dlerror();
char* buf = (char*) malloc(strlen(message) + 1 /* null */);
strcpy(buf, message);
return buf;
}
static inline char * STR_ERROR(int code) {
int i;
char* buf = NULL;
for(i = 256; i < (10 * 1024); i += 256) {
buf = (char*) malloc(i);
int res = strerror_r(code, buf, i);
if(res == 0) {
break;
}
free(buf);
buf = NULL;
if(res != ERANGE) {
break;
}
}
if(buf == NULL) {
int requiredBuffer = 25 /* static part*/ + 10 /* space for int */ + 1 /* null */;
buf = (char*) malloc(requiredBuffer);
snprintf(buf, requiredBuffer, "Failed to convert error: %d", code);
}
return buf;
}
#define FREE_LIBRARY(HANDLE) dlclose(HANDLE)
#define FIND_ENTRY(HANDLE, NAME) dlsym(HANDLE, NAME)
#endif
#ifdef _AIX
#undef DEFAULT_LOAD_OPTS
#define DEFAULT_LOAD_OPTS (RTLD_MEMBER| RTLD_LAZY | RTLD_GLOBAL)
#undef LOAD_LIBRARY
#define LOAD_LIBRARY(NAME,OPTS) dlopen(NAME, OPTS)
#endif
#include <stdlib.h>
#include <wchar.h>
#include <jni.h>
#ifndef NO_JAWT
#include <jawt.h>
#include <jawt_md.h>
#endif
#ifdef HAVE_PROTECTION
// When we have SEH, default to protection on
#if defined(_WIN32) && !(defined(_WIN64) && defined(__GNUC__))
static int _protect = 1;
#else
static int _protect;
#endif
#undef PROTECT
#define PROTECT _protect
#endif
#define CHARSET_UTF8 "utf8"
#ifdef __cplusplus
extern "C" {
#else
#include <stdbool.h>
#endif
#define MEMCPY(ENV,D,S,L) do { \
PSTART(); memcpy(D,S,L); PEND(ENV); \
} while(0)
#define MEMSET(ENV,D,C,L) do { \
PSTART(); memset(D,C,L); PEND(ENV); \
} while(0)
#define MASK_CC com_sun_jna_Function_MASK_CC
#define THROW_LAST_ERROR com_sun_jna_Function_THROW_LAST_ERROR
#define USE_VARARGS com_sun_jna_Function_USE_VARARGS
#define USE_VARARGS_SHIFT com_sun_jna_Function_USE_VARARGS_SHIFT
/* Cached class, field and method IDs */
static jclass classObject;
static jclass classClass;
static jclass classMethod;
static jclass classVoid, classPrimitiveVoid;
static jclass classBoolean, classPrimitiveBoolean;
static jclass classByte, classPrimitiveByte;
static jclass classCharacter, classPrimitiveCharacter;
static jclass classShort, classPrimitiveShort;
static jclass classInteger, classPrimitiveInteger;
static jclass classLong, classPrimitiveLong;
static jclass classFloat, classPrimitiveFloat;
static jclass classDouble, classPrimitiveDouble;
static jclass classString, classWString;
#ifndef NO_NIO_BUFFERS
static jclass classBuffer;
static jclass classByteBuffer;
static jclass classCharBuffer;
static jclass classShortBuffer;
static jclass classIntBuffer;
static jclass classLongBuffer;
static jclass classFloatBuffer;
static jclass classDoubleBuffer;
#endif /* NO_NIO_BUFFERS */
static jclass classPointer;
static jclass classNative;
static jclass classStructure;
static jclass classStructureByValue;
static jclass classCallback;
static jclass classCallbackReference;
static jclass classAttachOptions;
static jclass classNativeMapped;
static jclass classIntegerType;
static jclass classPointerType;
static jclass classJNIEnv;
static jclass class_ffi_callback;
static jclass classFromNativeConverter;
static jmethodID MID_Class_getComponentType;
static jmethodID MID_Object_toString;
static jmethodID MID_String_getBytes;
static jmethodID MID_String_getBytes2;
static jmethodID MID_String_toCharArray;
static jmethodID MID_String_init_bytes;
static jmethodID MID_String_init_bytes2;
static jmethodID MID_Method_getReturnType;
static jmethodID MID_Method_getParameterTypes;
static jmethodID MID_Long_init;
static jmethodID MID_Integer_init;
static jmethodID MID_Short_init;
static jmethodID MID_Character_init;
static jmethodID MID_Byte_init;
static jmethodID MID_Boolean_init;
static jmethodID MID_Float_init;
static jmethodID MID_Double_init;
#ifndef NO_NIO_BUFFERS
static jmethodID MID_Buffer_position;
static jmethodID MID_ByteBuffer_array;
static jmethodID MID_ByteBuffer_arrayOffset;
static jmethodID MID_CharBuffer_array;
static jmethodID MID_CharBuffer_arrayOffset;
static jmethodID MID_ShortBuffer_array;
static jmethodID MID_ShortBuffer_arrayOffset;
static jmethodID MID_IntBuffer_array;
static jmethodID MID_IntBuffer_arrayOffset;
static jmethodID MID_LongBuffer_array;
static jmethodID MID_LongBuffer_arrayOffset;
static jmethodID MID_FloatBuffer_array;
static jmethodID MID_FloatBuffer_arrayOffset;
static jmethodID MID_DoubleBuffer_array;
static jmethodID MID_DoubleBuffer_arrayOffset;
#endif /* NO_NIO_BUFFERS */
static jmethodID MID_Pointer_init;
static jmethodID MID_Native_dispose;
static jmethodID MID_Native_fromNativeCallbackParam;
static jmethodID MID_Native_fromNative;
static jmethodID MID_Native_nativeType;
static jmethodID MID_Native_toNativeTypeMapped;
static jmethodID MID_Native_fromNativeTypeMapped;
static jmethodID MID_Structure_getTypeInfo;
static jmethodID MID_Structure_newInstance;
static jmethodID MID_Structure_read;
static jmethodID MID_Structure_write;
static jmethodID MID_CallbackReference_getCallback;
static jmethodID MID_CallbackReference_getFunctionPointer;
static jmethodID MID_CallbackReference_getNativeString;
static jmethodID MID_CallbackReference_initializeThread;
static jmethodID MID_NativeMapped_toNative;
static jmethodID MID_WString_init;
static jmethodID MID_FromNativeConverter_nativeType;
static jmethodID MID_ffi_callback_invoke;
static jfieldID FID_Boolean_value;
static jfieldID FID_Byte_value;
static jfieldID FID_Short_value;
static jfieldID FID_Character_value;
static jfieldID FID_Integer_value;
static jfieldID FID_Long_value;
static jfieldID FID_Float_value;
static jfieldID FID_Double_value;
static jfieldID FID_Pointer_peer;
static jfieldID FID_Structure_memory;
static jfieldID FID_Structure_typeInfo;
static jfieldID FID_IntegerType_value;
static jfieldID FID_PointerType_pointer;
static int IS_BIG_ENDIAN;
jstring fileEncoding;
/* Forward declarations */
static char* newCString(JNIEnv *env, jstring jstr);
static char* newCStringEncoding(JNIEnv *env, jstring jstr, const char* encoding);
static wchar_t* newWideCString(JNIEnv *env, jstring jstr);
#ifndef NO_NIO_BUFFERS
static void* getBufferArray(JNIEnv*, jobject, jobject*, void **, void **);
static void* getDirectBufferAddress(JNIEnv*, jobject);
#endif
static char getArrayComponentType(JNIEnv *, jobject);
static ffi_type* getStructureType(JNIEnv *, jobject);
typedef void (JNICALL* release_t)(JNIEnv*,jarray,void*,jint);
#ifdef _WIN32
static char*
w32_format_error(int err) {
wchar_t* wbuf = NULL;
char* buf = NULL;
int wlen =
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM
|FORMAT_MESSAGE_IGNORE_INSERTS
|FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, err, 0, (LPWSTR)&wbuf, 0, NULL);
if (wlen > 0) {
int bufSize = WideCharToMultiByte(CP_UTF8, 0, wbuf, -1, NULL, 0, NULL, NULL);
buf = (char*)malloc(bufSize);
int result = WideCharToMultiByte(CP_UTF8, 0, wbuf, -1, buf, bufSize, NULL, NULL);
if (result == 0) {
fprintf(stderr, "JNA: error converting error message: %d\n", (int)GET_LAST_ERROR());
free(buf);
buf = NULL;
}
}
if (wbuf) {
LocalFree(wbuf);
}
return buf;
}
static wchar_t*
w32_short_name(JNIEnv* env, jstring str) {
wchar_t* wstr = newWideCString(env, str);
if (wstr && *wstr) {
DWORD required;
size_t size = wcslen(wstr) + 5;
wchar_t* prefixed = (wchar_t*)alloca(sizeof(wchar_t) * size);
swprintf(prefixed, size, L"\\\\?\\%ls", wstr);
if ((required = GetShortPathNameW(prefixed, NULL, 0)) != 0) {
wchar_t* wshort = (wchar_t*)malloc(sizeof(wchar_t) * required);
if (GetShortPathNameW(prefixed, wshort, required)) {
free((void *)wstr);
wstr = wshort;
}
else {
char* buf = LOAD_ERROR();
throwByName(env, EError, buf);
free((void *)buf);
free((void *)wstr);
free((void *)wshort);
wstr = NULL;
}
}
else if (GET_LAST_ERROR() != ERROR_FILE_NOT_FOUND) {
char* buf = LOAD_ERROR();
throwByName(env, EError, buf);
free((void *)buf);
free((void *)wstr);
wstr = NULL;
}
}
return wstr;
}
static HANDLE
w32_find_entry(JNIEnv* env, HANDLE handle, const char* funname) {
void* func = NULL;
if (handle != GetModuleHandle(NULL)) {
func = GetProcAddress(handle, funname);
}
else {
#if defined(_WIN32_WCE)
/* CE has no EnumProcessModules, have to use an alternate API */
HANDLE snapshot;
if ((snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0)) != INVALID_HANDLE_VALUE) {
MODULEENTRY32 moduleInfo;
moduleInfo.dwSize = sizeof(moduleInfo);
if (Module32First(snapshot, &moduleInfo)) {
do {
if ((func = (void *) GetProcAddress(moduleInfo.hModule, funname))) {
break;
}
} while (Module32Next(snapshot, &moduleInfo));
}
CloseToolhelp32Snapshot(snapshot);
}
#else
HANDLE cur_proc = GetCurrentProcess ();
HMODULE *modules;
DWORD needed, i;
if (!EnumProcessModules (cur_proc, NULL, 0, &needed)) {
fail:
throwByName(env, EError, "Unexpected error enumerating modules");
return 0;
}
modules = (HMODULE*) alloca (needed);
if (!EnumProcessModules (cur_proc, modules, needed, &needed)) {
goto fail;
}
for (i = 0; i < needed / sizeof (HMODULE); i++) {
if ((func = (void *) GetProcAddress (modules[i], funname))) {
break;
}
}
#endif
}
return func;
}
#endif /* _WIN32 */
#if 0
/** Invokes System.err.println (for debugging only). */
void
println(JNIEnv* env, const char* msg) {
jclass cls = (*env)->FindClass(env, "java/lang/System");
if (!cls) {
fprintf(stderr, "JNA: failed to find java.lang.System\n");
return;
}
jfieldID fid = (*env)->GetStaticFieldID(env, cls, "err",
"Ljava/io/PrintStream;");
jobject err = (*env)->GetStaticObjectField(env, cls, fid);
if (!err) {
fprintf(stderr, "JNA: failed to find System.err\n");
return;
}
jclass pscls = (*env)->FindClass(env, "java/io/PrintStream");
if (!pscls) {
fprintf(stderr, "JNA: failed to find java.io.PrintStream\n");
return;
}
jmethodID mid = (*env)->GetMethodID(env, pscls, "println",
"(Ljava/lang/String;)V");
jstring str = newJavaString(env, msg, CHARSET_UTF8);
(*env)->CallObjectMethod(env, err, mid, str);
}
#endif
/** Throw an exception by name */
void
throwByName(JNIEnv *env, const char *name, const char *msg)
{
jclass cls;
(*env)->ExceptionClear(env);
cls = (*env)->FindClass(env, name);
if (cls != NULL) { /* Otherwise an exception has already been thrown */
(*env)->ThrowNew(env, cls, msg);
/* It's a good practice to clean up the local references. */
(*env)->DeleteLocalRef(env, cls);
}
}
/** Translate FFI errors into exceptions. */
jboolean
ffi_error(JNIEnv* env, const char* op, ffi_status status) {
char msg[MSG_SIZE];
switch(status) {
case FFI_BAD_ABI:
snprintf(msg, sizeof(msg), "%s: Invalid calling convention (FFI_BAD_ABI)", op);
throwByName(env, EIllegalArgument, msg);
return JNI_TRUE;
case FFI_BAD_TYPEDEF:
snprintf(msg, sizeof(msg),
"%s: Invalid structure definition (native typedef error, FFI_BAD_TYPEDEF)", op);
throwByName(env, EIllegalArgument, msg);
return JNI_TRUE;
case FFI_BAD_ARGTYPE:
snprintf(msg, sizeof(msg),
"%s: Invalid argument type (FFI_BAD_ARGTYPE)", op);
throwByName(env, EIllegalArgument, msg);
return JNI_TRUE;
default:
snprintf(msg, sizeof(msg), "%s failed (%d)", op, status);
throwByName(env, EError, msg);
return JNI_TRUE;
case FFI_OK:
return JNI_FALSE;
}
}
/* invoke the real native function */
static void
dispatch(JNIEnv *env, void* func, jint flags, jobjectArray args,
ffi_type *return_type, void *presult)
{
int i, nargs;
jvalue* c_args;
char array_pt;
struct _array_elements {
jobject array;
void *elems;
release_t release;
} *array_elements;
volatile int array_count = 0;
ffi_cif cif;
ffi_type** arg_types;
void** arg_values;
ffi_abi abi;
ffi_status status;
char msg[MSG_SIZE];
callconv_t callconv = flags & MASK_CC;
const char* volatile throw_type = NULL;
const char* volatile throw_msg = NULL;
int fixed_args = (flags >> USE_VARARGS_SHIFT) & USE_VARARGS;
nargs = (*env)->GetArrayLength(env, args);
if (nargs > MAX_NARGS) {
snprintf(msg, sizeof(msg), "Too many arguments (max %ld)", MAX_NARGS);
throwByName(env, EUnsupportedOperation, msg);
return;
}
c_args = (jvalue*)alloca(nargs * sizeof(jvalue));
array_elements = (struct _array_elements*)
alloca(nargs * sizeof(struct _array_elements));
arg_types = (ffi_type**)alloca(nargs * sizeof(ffi_type*));
arg_values = (void**)alloca(nargs * sizeof(void*));
for (i = 0; i < nargs; i++) {
jobject arg = (*env)->GetObjectArrayElement(env, args, i);
if (arg == NULL) {
c_args[i].l = NULL;
arg_types[i] = &ffi_type_pointer;
arg_values[i] = &c_args[i].l;
}
else if ((*env)->IsInstanceOf(env, arg, classBoolean)) {
c_args[i].i = (*env)->GetBooleanField(env, arg, FID_Boolean_value);
arg_types[i] = &ffi_type_uint32;
arg_values[i] = &c_args[i].i;
}
else if ((*env)->IsInstanceOf(env, arg, classByte)) {
c_args[i].b = (*env)->GetByteField(env, arg, FID_Byte_value);
// Promote char to int if we prepare a varargs call
if(fixed_args && i >= fixed_args && sizeof(char) < sizeof(int)) {
arg_types[i] = &ffi_type_uint32;
arg_values[i] = alloca(sizeof(int));
*(int*)arg_values[i] = (int) c_args[i].b;
} else {
arg_types[i] = &ffi_type_sint8;
arg_values[i] = &c_args[i].b;
}
}
else if ((*env)->IsInstanceOf(env, arg, classShort)) {
c_args[i].s = (*env)->GetShortField(env, arg, FID_Short_value);
// Promote short to int if we prepare a varargs call
if(fixed_args && i >= fixed_args && sizeof(short) < sizeof(int)) {
arg_types[i] = &ffi_type_uint32;
arg_values[i] = alloca(sizeof(int));
*(int*)arg_values[i] = (int) c_args[i].s;
} else {
arg_types[i] = &ffi_type_sint16;
arg_values[i] = &c_args[i].s;
}
}
else if ((*env)->IsInstanceOf(env, arg, classCharacter)) {
if (sizeof(wchar_t) == 2) {
c_args[i].c = (*env)->GetCharField(env, arg, FID_Character_value);
if(fixed_args && i >= fixed_args && sizeof(short) < sizeof(int)) {
arg_types[i] = &ffi_type_uint32;
arg_values[i] = alloca(sizeof(int));
*(int*)arg_values[i] = (int) c_args[i].c;
} else {
arg_types[i] = &ffi_type_uint16;
arg_values[i] = &c_args[i].c;
}
}
else if (sizeof(wchar_t) == 4) {
c_args[i].i = (*env)->GetCharField(env, arg, FID_Character_value);
arg_types[i] = &ffi_type_uint32;
arg_values[i] = &c_args[i].i;
}
else {
snprintf(msg, sizeof(msg), "Unsupported wchar_t size (%d)", (int)sizeof(wchar_t));
throw_type = EUnsupportedOperation;
throw_msg = msg;
goto cleanup;
}
}
else if ((*env)->IsInstanceOf(env, arg, classInteger)) {
c_args[i].i = (*env)->GetIntField(env, arg, FID_Integer_value);
arg_types[i] = &ffi_type_sint32;
arg_values[i] = &c_args[i].i;
}
else if ((*env)->IsInstanceOf(env, arg, classLong)) {
c_args[i].j = (*env)->GetLongField(env, arg, FID_Long_value);
arg_types[i] = &ffi_type_sint64;
arg_values[i] = &c_args[i].j;
}
else if ((*env)->IsInstanceOf(env, arg, classFloat)) {
c_args[i].f = (*env)->GetFloatField(env, arg, FID_Float_value);
arg_types[i] = &ffi_type_float;
arg_values[i] = &c_args[i].f;
}
else if ((*env)->IsInstanceOf(env, arg, classDouble)) {
c_args[i].d = (*env)->GetDoubleField(env, arg, FID_Double_value);
arg_types[i] = &ffi_type_double;
arg_values[i] = &c_args[i].d;
}
else if ((*env)->IsInstanceOf(env, arg, classPointer)) {
c_args[i].l = getNativeAddress(env, arg);
arg_types[i] = &ffi_type_pointer;
arg_values[i] = &c_args[i].l;
}
else if ((*env)->IsInstanceOf(env, arg, classJNIEnv)) {
c_args[i].l = (void*)env;
arg_types[i] = &ffi_type_pointer;
arg_values[i] = &c_args[i].l;
}
else if ((*env)->IsInstanceOf(env, arg, classStructure)) {
c_args[i].l = getStructureAddress(env, arg);
arg_types[i] = getStructureType(env, arg);
arg_values[i] = c_args[i].l;
if (!arg_types[i]) {
snprintf(msg, sizeof(msg),
"Structure type info not initialized at argument %d", i);
throw_type = EIllegalState;
throw_msg = msg;
goto cleanup;
}
}
#ifndef NO_NIO_BUFFERS
else if ((*env)->IsInstanceOf(env, arg, classBuffer)) {
c_args[i].l = getDirectBufferAddress(env, arg);
arg_types[i] = &ffi_type_pointer;
arg_values[i] = &c_args[i].l;
if (c_args[i].l == NULL) {
c_args[i].l =
getBufferArray(env, arg, &array_elements[array_count].array,
&array_elements[array_count].elems,
(void**)&array_elements[array_count].release);
if (c_args[i].l == NULL) {
throw_type = EIllegalArgument;
throw_msg = "Buffer arguments must be direct or have a primitive backing array";
goto cleanup;
}
++array_count;
}
}
#endif /* NO_NIO_BUFFERS */
else if ((array_pt = getArrayComponentType(env, arg)) != 0
&& array_pt != 'L') {
void *ptr = NULL;
release_t release = NULL;
#define GET_ELEMS(TYPE) do {ptr=(*env)->Get##TYPE##ArrayElements(env,arg,NULL); release=(void*)(*env)->Release##TYPE##ArrayElements; }while(0)
switch(array_pt) {
case 'Z': GET_ELEMS(Boolean); break;
case 'B': GET_ELEMS(Byte); break;
case 'C': GET_ELEMS(Char); break;
case 'S': GET_ELEMS(Short); break;
case 'I': GET_ELEMS(Int); break;
case 'J': GET_ELEMS(Long); break;
case 'F': GET_ELEMS(Float); break;
case 'D': GET_ELEMS(Double); break;
}
if (!ptr) {
throw_type = EOutOfMemory;
throw_msg = "Could not obtain memory for primitive buffer";
goto cleanup;
}
c_args[i].l = ptr;
arg_types[i] = &ffi_type_pointer;
arg_values[i] = &c_args[i].l;
array_elements[array_count].array = arg;
array_elements[array_count].elems = ptr;
array_elements[array_count++].release = release;
}
else {
// Anything else, pass directly as a pointer
c_args[i].l = (void*)arg;
arg_types[i] = &ffi_type_pointer;
arg_values[i] = &c_args[i].l;
}
}
switch (callconv) {
case CALLCONV_C:
abi = FFI_DEFAULT_ABI;
break;
#ifdef _WIN32
case CALLCONV_STDCALL:
#if defined(_WIN64) || defined(_WIN32_WCE)
// Ignore requests for stdcall on win64/wince
abi = FFI_DEFAULT_ABI;
#else
abi = FFI_STDCALL;
#endif
break;
#endif // _WIN32
default:
abi = (int)callconv;
if (!(abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI)) {
snprintf(msg, sizeof(msg),
"Unrecognized calling convention: %d", abi);
throw_type = EIllegalArgument;
throw_msg = msg;
goto cleanup;
}
break;
}
status = fixed_args
? ffi_prep_cif_var(&cif, abi, fixed_args, nargs, return_type, arg_types)
: ffi_prep_cif(&cif, abi, nargs, return_type, arg_types);
if (!ffi_error(env, "Native call setup", status)) {
PSTART();
if ((flags & THROW_LAST_ERROR) != 0) {
SET_LAST_ERROR(0);
}
ffi_call(&cif, FFI_FN(func), presult, arg_values);
{
int err = GET_LAST_ERROR();
JNA_set_last_error(env, err);
if ((flags & THROW_LAST_ERROR) && err) {
char* emsg = STR_ERROR(err);
snprintf(msg, MSG_SIZE, "[%d] %s", err, emsg);
free(emsg);
throw_type = ELastError;
throw_msg = msg;
}
}
PROTECTED_END(do { throw_type=EError;throw_msg="Invalid memory access";} while(0));
}
cleanup:
// Release array elements
for (i=0;i < array_count;i++) {
array_elements[i].release(env, array_elements[i].array,
array_elements[i].elems, 0);
}
// Must raise any exception *after* all other JNI operations
if (throw_type) {
throwByName(env, throw_type, throw_msg);
}
}
/** Copy characters from the Java character array into native memory. */
static void
getChars(JNIEnv* env, wchar_t* volatile dst, jcharArray chars, volatile jint off, volatile jint len) {
PSTART();
if (sizeof(jchar) == sizeof(wchar_t)) {
(*env)->GetCharArrayRegion(env, chars, off, len, (jchar*)dst);
}
else {
jchar* buf;
int count = len > 1000 ? 1000 : len;
buf = (jchar *)alloca(count * sizeof(jchar));
if (!buf) {
throwByName(env, EOutOfMemory, "Can't read characters");
}
else {
while (len > 0) {
int i;
(*env)->GetCharArrayRegion(env, chars, off, count, buf);
for (i=0;i < count;i++) {
// TODO: ensure proper encoding conversion from jchar to native
// wchar_t
dst[i] = (wchar_t)buf[i];
}
dst += count;
off += count;
len -= count;
if (count > len) count = len;
}
}
}
PEND(env);
}
static void
setChars(JNIEnv* env, wchar_t* src, jcharArray chars, volatile jint off, volatile jint len) {
jchar* buf = (jchar*)src;
PSTART();
if (sizeof(jchar) == sizeof(wchar_t)) {
(*env)->SetCharArrayRegion(env, chars, off, len, buf);
}
else {
int count = len > 1000 ? 1000 : len;
buf = (jchar *)alloca(count * sizeof(jchar));
if (!buf) {
throwByName(env, EOutOfMemory, "Can't write characters");
}
else {
while (len > 0) {
int i;
for (i=0;i < count;i++) {
buf[i] = (jchar)src[off+i];
}
(*env)->SetCharArrayRegion(env, chars, off, count, buf);
off += count;
len -= count;
if (count > len) count = len;
}
}
}
PEND(env);
}
/* Translates a Java string to a C string using the
* String.getBytes(byte[],String), using the requested encoding.
*/
static char *
newCString(JNIEnv *env, jstring jstr)
{
jbyteArray bytes = 0;
char *result = NULL;
bytes = (*env)->CallObjectMethod(env, jstr, MID_String_getBytes);
if (!(*env)->ExceptionCheck(env)) {
jint len = (*env)->GetArrayLength(env, bytes);
result = (char *)malloc(len + 1);
if (result == NULL) {
(*env)->DeleteLocalRef(env, bytes);
throwByName(env, EOutOfMemory, "Can't allocate C string");
return NULL;
}
(*env)->GetByteArrayRegion(env, bytes, 0, len, (jbyte *)result);
result[len] = 0; /* NUL-terminate */
}
(*env)->DeleteLocalRef(env, bytes);
return result;
}
/* Translates a Java string to a C string using the String.getBytes("UTF8")
* method, which uses UTF8 encoding.
*/
const char *
newCStringUTF8(JNIEnv *env, jstring jstr)
{
return newCStringEncoding(env, jstr, CHARSET_UTF8);
}
static char*
newCStringEncoding(JNIEnv *env, jstring jstr, const char* encoding)
{
jbyteArray bytes = 0;
char *result = NULL;
if (!encoding) return newCString(env, jstr);
bytes = (*env)->CallObjectMethod(env, jstr, MID_String_getBytes2,
newJavaString(env, encoding, CHARSET_UTF8));
if (!(*env)->ExceptionCheck(env)) {
jint len = (*env)->GetArrayLength(env, bytes);
result = (char *)malloc(len + 1);
if (result == NULL) {
(*env)->DeleteLocalRef(env, bytes);
throwByName(env, EOutOfMemory, "Can't allocate C string");
return NULL;
}
(*env)->GetByteArrayRegion(env, bytes, 0, len, (jbyte *)result);
result[len] = 0; /* NUL-terminate */
}
(*env)->DeleteLocalRef(env, bytes);
return result;
}
/* Translates a Java string to a wide C string using the String.toCharArray
* method.
*/
static wchar_t *
newWideCString(JNIEnv *env, jstring str)
{
jcharArray chars = 0;
wchar_t *result = NULL;
if ((*env)->IsSameObject(env, str, NULL)) {
return result;
}
chars = (*env)->CallObjectMethod(env, str, MID_String_toCharArray);
if (!(*env)->ExceptionCheck(env)) {
jint len = (*env)->GetArrayLength(env, chars);
result = (wchar_t *)malloc(sizeof(wchar_t) * (len + 1));
if (result == NULL) {
(*env)->DeleteLocalRef(env, chars);
throwByName(env, EOutOfMemory, "Can't allocate wide C string");
return NULL;
}
getChars(env, result, chars, 0, len);
if ((*env)->ExceptionCheck(env)) {
free((void *)result);
result = NULL;
}
else {
result[len] = 0; /* NUL-terminate */
}
}
(*env)->DeleteLocalRef(env, chars);
return result;
}
jobject
newJavaWString(JNIEnv *env, const wchar_t* ptr) {
if (ptr) {
jstring s = newJavaString(env, (const char*)ptr, NULL);
return (*env)->NewObject(env, classWString, MID_WString_init, s);
}
return NULL;
}
jstring
encodingString(JNIEnv *env, const char* ptr) {
jstring result = NULL;
jbyteArray bytes = 0;
int len = (int)strlen((const char*)ptr);
bytes = (*env)->NewByteArray(env, len);
if (bytes != NULL) {
(*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte *)ptr);
result = (*env)->NewObject(env, classString,
MID_String_init_bytes, bytes);
(*env)->DeleteLocalRef(env, bytes);
}
return result;
}
/* Constructs a Java string from a char array (using the String(byte[],String)
* constructor) or a short array (using the
* String(char[]) ctor, which uses the character values unmodified).
*/
jstring
newJavaString(JNIEnv *env, const char *ptr, const char* charset)
{
volatile jstring result = 0;
PSTART();
if (ptr) {
if (charset == NULL) {
// TODO: proper conversion from native wchar_t to jchar, if any
jsize len = (int)wcslen((const wchar_t*)ptr);
if (sizeof(jchar) != sizeof(wchar_t)) {
// NOTE: while alloca may succeed here, writing to the stack
// memory may fail with really large buffers
jchar* buf = (jchar*)malloc(len * sizeof(jchar));
if (!buf) {
throwByName(env, EOutOfMemory, "Can't allocate space for conversion to Java String");
}
else {
int i;
for (i=0;i < len;i++) {
buf[i] = *((const wchar_t*)ptr + i);
}
result = (*env)->NewString(env, buf, len);
free((void*)buf);
}
}
else {
result = (*env)->NewString(env, (const jchar*)ptr, len);
}
}
else {
jbyteArray bytes = 0;
int len = (int)strlen((const char*)ptr);
bytes = (*env)->NewByteArray(env, len);
if (bytes != NULL) {
(*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte *)ptr);
result = (*env)->NewObject(env, classString,
MID_String_init_bytes2, bytes,
encodingString(env, charset));
(*env)->DeleteLocalRef(env, bytes);
}
}
}
PEND(env);
return result;
}
jobject
newJavaPointer(JNIEnv *env, void *p)
{
jobject obj = NULL;
if (p != NULL) {
obj = (*env)->NewObject(env, classPointer, MID_Pointer_init, A2L(p));
}
return obj;
}
jobject
newJavaStructure(JNIEnv *env, void *data, jclass type)
{
if (data != NULL) {
volatile jobject obj = (*env)->CallStaticObjectMethod(env, classStructure, MID_Structure_newInstance, type, A2L(data));
if (obj == NULL) {
fprintf(stderr, "JNA: failed to create structure\n");
}
return obj;
}
return NULL;
}
jobject
newJavaCallback(JNIEnv* env, void* fptr, jclass type)
{
if (fptr != NULL) {
jobject ptr = newJavaPointer(env, fptr);
return (*env)->CallStaticObjectMethod(env, classCallbackReference,
MID_CallbackReference_getCallback,
type, ptr, JNI_TRUE);
}
return NULL;
}
void*
getNativeString(JNIEnv* env, jstring s, jboolean wide) {
if (s != NULL) {
jobject ptr = (*env)->CallStaticObjectMethod(env, classCallbackReference,
MID_CallbackReference_getNativeString,
s, wide);
if (!(*env)->ExceptionCheck(env)) {
return getNativeAddress(env, ptr);