chef-win32-api 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/ext/win32/api.c ADDED
@@ -0,0 +1,1159 @@
1
+ #include <ruby.h>
2
+ #include <windows.h>
3
+
4
+ // Ruby 1.9.x
5
+ #ifndef RSTRING_PTR
6
+ #define RSTRING_PTR(s) (RSTRING(s)->ptr)
7
+ #endif
8
+ #ifndef RSTRING_LEN
9
+ #define RSTRING_LEN(s) (RSTRING(s)->len)
10
+ #endif
11
+
12
+ #ifndef RARRAY_PTR
13
+ #define RARRAY_PTR(a) (RARRAY(a)->ptr)
14
+ #endif
15
+ #ifndef RARRAY_LEN
16
+ #define RARRAY_LEN(a) (RARRAY(a)->len)
17
+ #endif
18
+
19
+ /* Use Ruby defined macro definitions. */
20
+ #if !defined(NUM2SIZET) && !defined(NUM2SSIZET)
21
+ # if defined(HAVE_LONG_LONG) && SIZEOF_SIZE_T > SIZEOF_LONG
22
+ # define NUM2SIZET(x) ((size_t)NUM2ULL(x))
23
+ # define NUM2SSIZET(x) ((ssize_t)NUM2LL(x))
24
+ # else
25
+ # define NUM2SIZET(x) NUM2ULONG(x)
26
+ # define NUM2SSIZET(x) NUM2LONG(x)
27
+ # endif
28
+ #endif
29
+
30
+ /* Use Ruby defined macro definitions. */
31
+ #if !defined(SIZET2NUM) && !defined(SSIZET2NUM)
32
+ # if SIZEOF_SIZE_T > SIZEOF_LONG && defined(HAVE_LONG_LONG)
33
+ # define SIZET2NUM(v) ULL2NUM(v)
34
+ # define SSIZET2NUM(v) LL2NUM(v)
35
+ # elif SIZEOF_SIZE_T == SIZEOF_LONG
36
+ # define SIZET2NUM(v) ULONG2NUM(v)
37
+ # define SSIZET2NUM(v) LONG2NUM(v)
38
+ # else
39
+ # define SIZET2NUM(v) UINT2NUM(v)
40
+ # define SSIZET2NUM(v) INT2NUM(v)
41
+ # endif
42
+ #endif
43
+
44
+
45
+ #define MAX_BUF 1024
46
+ #define WINDOWS_API_VERSION "1.10.1"
47
+
48
+ #define _T_VOID 0
49
+ #define _T_LONG 1
50
+ #define _T_POINTER 2
51
+ #define _T_INTEGER 3
52
+ #define _T_CALLBACK 4
53
+ #define _T_STRING 5
54
+
55
+ VALUE cAPIError, cAPIProtoError, cAPILoadError;
56
+ static VALUE ActiveCallback = Qnil;
57
+
58
+ typedef struct {
59
+ HANDLE library;
60
+ FARPROC function;
61
+ int return_type;
62
+ int prototype[20];
63
+ } Win32API;
64
+
65
+ typedef struct ThreadData {
66
+ DWORD win32api_error;
67
+ } ThreadData;
68
+
69
+ static inline ThreadData* thread_data_get(void);
70
+ static ID id_thread_data;
71
+
72
+ static ThreadData* thread_data_init(void)
73
+ {
74
+ ThreadData* td;
75
+ VALUE obj;
76
+
77
+ obj = Data_Make_Struct(rb_cObject, ThreadData, NULL, -1, td);
78
+ td->win32api_error = 0;
79
+ rb_thread_local_aset(rb_thread_current(), id_thread_data, obj);
80
+
81
+ return td;
82
+ }
83
+
84
+ static inline ThreadData* thread_data_get()
85
+ {
86
+ VALUE obj = rb_thread_local_aref(rb_thread_current(), id_thread_data);
87
+
88
+ if(obj != Qnil && TYPE(obj) == T_DATA){
89
+ return (ThreadData*) DATA_PTR(obj);
90
+ }
91
+
92
+ return thread_data_init();
93
+ }
94
+
95
+ static void api_free(Win32API* ptr){
96
+ if(ptr->library)
97
+ FreeLibrary(ptr->library);
98
+
99
+ if(ptr)
100
+ free(ptr);
101
+ }
102
+
103
+ static VALUE api_allocate(VALUE klass){
104
+ Win32API* ptr = malloc(sizeof(Win32API));
105
+ memset(ptr, 0, sizeof(*ptr));
106
+ return Data_Wrap_Struct(klass, 0, api_free, ptr);
107
+ }
108
+
109
+ /* Helper function that converts the error number returned by GetLastError()
110
+ * into a human readable string. Note that we always use English for error
111
+ * output because that's what Ruby itself does.
112
+ *
113
+ * Internal use only.
114
+ */
115
+ char* StringError(DWORD dwError){
116
+ LPVOID lpMsgBuf;
117
+ static char buf[MAX_PATH];
118
+ DWORD dwLen, dwLastError;
119
+
120
+ // Assume ASCII (English) error messages from the Windows API
121
+ dwLen = FormatMessageA(
122
+ FORMAT_MESSAGE_ALLOCATE_BUFFER |
123
+ FORMAT_MESSAGE_FROM_SYSTEM |
124
+ FORMAT_MESSAGE_IGNORE_INSERTS,
125
+ NULL,
126
+ dwError,
127
+ MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
128
+ (LPSTR)&lpMsgBuf,
129
+ 0,
130
+ NULL
131
+ );
132
+
133
+ dwLastError = GetLastError();
134
+
135
+ /* It appears that Windows doesn't necessarily ship with the DLL
136
+ * required to always use English error messages. Check for error
137
+ * ERROR_MUI_FILE_NOT_FOUND (15100) or ERROR_RESOURCE_LANG_NOT_FOUND (1815)
138
+ * and try again if necessary.
139
+ */
140
+ if(!dwLen && (dwLastError == 15100 || dwLastError == 1815)){
141
+ dwLen = FormatMessageA(
142
+ FORMAT_MESSAGE_ALLOCATE_BUFFER |
143
+ FORMAT_MESSAGE_FROM_SYSTEM |
144
+ FORMAT_MESSAGE_IGNORE_INSERTS,
145
+ NULL,
146
+ dwError,
147
+ 0,
148
+ (LPSTR)&lpMsgBuf,
149
+ 0,
150
+ NULL
151
+ );
152
+ }
153
+
154
+ if(!dwLen){
155
+ rb_raise(
156
+ cAPIError,
157
+ "Attempt to format message failed (error = '%lu')",
158
+ GetLastError()
159
+ );
160
+ }
161
+
162
+ memset(buf, 0, MAX_PATH);
163
+
164
+ // Remove \r\n at end of string.
165
+ #ifdef HAVE_STRNCPY_S
166
+ strncpy_s(buf, MAX_PATH, lpMsgBuf, dwLen - 2);
167
+ #else
168
+ strncpy(buf, lpMsgBuf, dwLen - 2);
169
+ #endif
170
+
171
+ LocalFree(lpMsgBuf);
172
+
173
+ return buf;
174
+ }
175
+
176
+ /*
177
+ * call-seq:
178
+ * Win32::API::Callback.new(prototype, return='L'){ |proto| ... }
179
+ *
180
+ * Creates and returns a new Win32::API::Callback object. The prototype
181
+ * arguments are yielded back to the block in the same order they were
182
+ * declared.
183
+ *
184
+ * The +prototype+ is the function prototype for the callback function. This
185
+ * is a string. The possible valid characters are 'I' (integer), 'L' (long),
186
+ * 'V' (void), 'P' (pointer) or 'S' (string). Unlike API objects, API::Callback
187
+ * objects do not have a default prototype.
188
+ *
189
+ * The +return+ argument is the return type for the callback function. The
190
+ * valid characters are the same as for the +prototype+. The default is
191
+ * 'L' (long).
192
+ *
193
+ * Example:
194
+ * require 'win32/api'
195
+ * include Win32
196
+ *
197
+ * EnumWindows = API.new('EnumWindows', 'KP', 'L', 'user32')
198
+ * GetWindowText = API.new('GetWindowText', 'LPI', 'I', 'user32')
199
+ *
200
+ * EnumWindowsProc = API::Callback.new('LP', 'I'){ |handle, param|
201
+ * buf = "\0" * 200
202
+ * GetWindowText.call(handle, buf, 200);
203
+ * puts buf.strip unless buf.strip.empty?
204
+ * buf.index(param).nil? ? true : false
205
+ * }
206
+ *
207
+ * EnumWindows.call(EnumWindowsProc, 'UEDIT32')
208
+ */
209
+ static VALUE callback_init(int argc, VALUE* argv, VALUE self)
210
+ {
211
+ void *find_callback(VALUE,int);
212
+ VALUE v_proto, v_return, v_proc;
213
+ int i;
214
+
215
+ rb_scan_args(argc, argv, "11&", &v_proto, &v_return, &v_proc);
216
+
217
+ /* Validate prototype characters */
218
+ for(i = 0; i < RSTRING_LEN(v_proto); i++){
219
+ switch(RSTRING_PTR(v_proto)[i]){
220
+ case 'I': case 'L': case 'P': case 'V': case 'S':
221
+ break;
222
+ default:
223
+ rb_raise(cAPIProtoError, "Illegal prototype '%c'",
224
+ RSTRING_PTR(v_proto)[i]
225
+ );
226
+ }
227
+ }
228
+
229
+ if(NIL_P(v_return) || RARRAY_LEN(v_return) == 0){
230
+ v_return = rb_str_new2("L");
231
+ }
232
+ else{
233
+ switch(*(TCHAR*)RSTRING_PTR(v_return)){
234
+ case 'I': case 'L': case 'P': case 'V': case 'S':
235
+ break;
236
+ default:
237
+ rb_raise(cAPIProtoError, "Illegal return type '%s'",
238
+ RSTRING_PTR(v_return)
239
+ );
240
+ }
241
+ }
242
+
243
+ rb_iv_set(self, "@function", v_proc);
244
+ rb_iv_set(self, "@prototype", v_proto);
245
+ rb_iv_set(self, "@return_type", v_return);
246
+ rb_iv_set(self, "@address", SIZET2NUM((LPARAM)find_callback(self,RSTRING_LEN(v_proto))));
247
+ ActiveCallback = self;
248
+
249
+ return self;
250
+ }
251
+
252
+ /*
253
+ * call-seq:
254
+ * Win32::API.new(function, prototype='V', return='L', dll='kernel32')
255
+ *
256
+ * Creates and returns a new Win32::API object. The +function+ is the name
257
+ * of the Windows function.
258
+ *
259
+ * The +prototype+ is the function prototype for +function+. This can be a
260
+ * string or an array of characters. The possible valid characters are 'I'
261
+ * (integer), 'L' (long), 'V' (void), 'P' (pointer), 'K' (callback) or 'S'
262
+ * (string).
263
+ *
264
+ * The default is void ('V').
265
+ *
266
+ * Constant (const char*) strings should use 'S'. Pass by reference string
267
+ * buffers should use 'P'. The former is faster, but cannot be modified.
268
+ *
269
+ * The +return+ argument is the return type for the function. The valid
270
+ * characters are the same as for the +prototype+. The default is 'L' (long).
271
+ *
272
+ * The +dll+ is the name of the DLL file that the function is exported from.
273
+ * The default is 'kernel32'.
274
+ *
275
+ * If the function cannot be found then an API::Error is raised (a subclass
276
+ * of RuntimeError).
277
+ *
278
+ * Example:
279
+ *
280
+ * require 'win32/api'
281
+ * include Win32
282
+ *
283
+ * buf = 0.chr * 260
284
+ * len = [buf.length].pack('L')
285
+ *
286
+ * GetUserName = API.new('GetUserName', 'PP', 'I', 'advapi32')
287
+ * GetUserName.call(buf, len)
288
+ *
289
+ * puts buf.strip
290
+ */
291
+ static VALUE api_init(int argc, VALUE* argv, VALUE self)
292
+ {
293
+ HMODULE hLibrary;
294
+ FARPROC fProc;
295
+ Win32API* ptr;
296
+ int i;
297
+ const char* first = "A";
298
+ const char* second = "W";
299
+ VALUE v_proc, v_proto, v_return, v_dll;
300
+
301
+ rb_scan_args(argc, argv, "13", &v_proc, &v_proto, &v_return, &v_dll);
302
+
303
+ Data_Get_Struct(self, Win32API, ptr);
304
+
305
+ // Convert a string prototype to an array of characters
306
+ if(rb_respond_to(v_proto, rb_intern("split")))
307
+ v_proto = rb_str_split(v_proto, "");
308
+
309
+ // Convert a nil or empty prototype to 'V' (void) automatically
310
+ if(NIL_P(v_proto) || RARRAY_LEN(v_proto) == 0){
311
+ v_proto = rb_ary_new();
312
+ rb_ary_push(v_proto, rb_str_new2("V"));
313
+ }
314
+
315
+ // Set an arbitrary limit of 20 parameters
316
+ if(RARRAY_LEN(v_proto) > 20)
317
+ rb_raise(rb_eArgError, "too many parameters: %ld", RARRAY_LEN(v_proto));
318
+
319
+ // Set the default dll to 'kernel32'
320
+ if(NIL_P(v_dll))
321
+ v_dll = rb_str_new2("kernel32");
322
+
323
+ // Set the default return type to 'L' (DWORD)
324
+ if(NIL_P(v_return))
325
+ v_return = rb_str_new2("L");
326
+
327
+ #if defined TAINTING_SUPPORT
328
+ SafeStringValue(v_dll);
329
+ SafeStringValue(v_proc);
330
+ #endif
331
+
332
+ hLibrary = LoadLibrary(TEXT(RSTRING_PTR(v_dll)));
333
+
334
+ // The most likely cause of failure is a bad DLL load path
335
+ if(!hLibrary){
336
+ rb_raise(cAPILoadError, "LoadLibrary() function failed for '%s': %s",
337
+ RSTRING_PTR(v_dll),
338
+ StringError(GetLastError())
339
+ );
340
+ }
341
+
342
+ ptr->library = hLibrary;
343
+
344
+ /* Attempt to get the function. If it fails, try again with an 'A'
345
+ * appended. If that fails, try again with a 'W' appended. If that
346
+ * still fails, raise an API::LoadLibraryError.
347
+ */
348
+
349
+ fProc = GetProcAddress(hLibrary, TEXT(RSTRING_PTR(v_proc)));
350
+
351
+ // Skip the ANSI and Wide function checks for MSVCRT functions.
352
+ if(!fProc){
353
+ if(strstr(RSTRING_PTR(v_dll), "msvcr")){
354
+ rb_raise(
355
+ cAPILoadError,
356
+ "Unable to load function '%s'",
357
+ RSTRING_PTR(v_proc)
358
+ );
359
+ }
360
+ else{
361
+ VALUE v_ascii = rb_str_new3(v_proc);
362
+ v_ascii = rb_str_cat(v_ascii, first, 1);
363
+ fProc = GetProcAddress(hLibrary, TEXT(RSTRING_PTR(v_ascii)));
364
+
365
+ if(!fProc){
366
+ VALUE v_unicode = rb_str_new3(v_proc);
367
+ v_unicode = rb_str_cat(v_unicode, second, 1);
368
+ fProc = GetProcAddress(hLibrary, TEXT(RSTRING_PTR(v_unicode)));
369
+
370
+ if(!fProc){
371
+ rb_raise(
372
+ cAPILoadError,
373
+ "Unable to load function '%s', '%s', or '%s'",
374
+ RSTRING_PTR(v_proc),
375
+ RSTRING_PTR(v_ascii),
376
+ RSTRING_PTR(v_unicode)
377
+ );
378
+ }
379
+ else{
380
+ rb_iv_set(self, "@effective_function_name", v_unicode);
381
+ }
382
+ }
383
+ else{
384
+ rb_iv_set(self, "@effective_function_name", v_ascii);
385
+ }
386
+ }
387
+ }
388
+ else{
389
+ rb_iv_set(self, "@effective_function_name", v_proc);
390
+ }
391
+
392
+ ptr->function = fProc;
393
+
394
+ // Push the numeric prototypes onto our int array for later use.
395
+
396
+ for(i = 0; i < RARRAY_LEN(v_proto); i++){
397
+ #if defined TAINTING_SUPPORT
398
+ SafeStringValue(RARRAY_PTR(v_proto)[i]);
399
+ #endif
400
+ switch(*(TCHAR*)StringValuePtr(RARRAY_PTR(v_proto)[i])){
401
+ case 'L':
402
+ ptr->prototype[i] = _T_LONG;
403
+ break;
404
+ case 'P':
405
+ ptr->prototype[i] = _T_POINTER;
406
+ break;
407
+ case 'I': case 'B':
408
+ ptr->prototype[i] = _T_INTEGER;
409
+ break;
410
+ case 'V':
411
+ ptr->prototype[i] = _T_VOID;
412
+ break;
413
+ case 'K':
414
+ ptr->prototype[i] = _T_CALLBACK;
415
+ break;
416
+ case 'S':
417
+ ptr->prototype[i] = _T_STRING;
418
+ break;
419
+ default:
420
+ rb_raise(cAPIProtoError, "Illegal prototype '%s'",
421
+ StringValuePtr(RARRAY_PTR(v_proto)[i])
422
+ );
423
+ }
424
+ }
425
+
426
+ // Store the return type for later use.
427
+
428
+ // Automatically convert empty strings or nil to type void.
429
+ if(NIL_P(v_return) || RSTRING_LEN(v_return) == 0){
430
+ v_return = rb_str_new2("V");
431
+ ptr->return_type = _T_VOID;
432
+ }
433
+ else{
434
+ #if defined TAINTING_SUPPORT
435
+ SafeStringValue(v_return);
436
+ #endif
437
+ switch(*RSTRING_PTR(v_return)){
438
+ case 'L':
439
+ ptr->return_type = _T_LONG;
440
+ break;
441
+ case 'P':
442
+ ptr->return_type = _T_POINTER;
443
+ break;
444
+ case 'I': case 'B':
445
+ ptr->return_type = _T_INTEGER;
446
+ break;
447
+ case 'V':
448
+ ptr->return_type = _T_VOID;
449
+ break;
450
+ case 'S':
451
+ ptr->return_type = _T_STRING;
452
+ break;
453
+ default:
454
+ rb_raise(cAPIProtoError, "Illegal return type '%s'",
455
+ RSTRING_PTR(v_return)
456
+ );
457
+ }
458
+ }
459
+
460
+ rb_iv_set(self, "@dll_name", v_dll);
461
+ rb_iv_set(self, "@function_name", v_proc);
462
+ rb_iv_set(self, "@prototype", v_proto);
463
+ rb_iv_set(self, "@return_type", v_return);
464
+
465
+ return self;
466
+ }
467
+
468
+ /*
469
+ * call-seq:
470
+ *
471
+ * API::Function.new(address, prototype = 'V', return_type = 'L')
472
+ *
473
+ * Creates and returns an API::Function object. This object is similar to an
474
+ * API object, except that instead of a character function name you pass a
475
+ * function pointer address as the first argument, and there's no associated
476
+ * DLL file.
477
+ *
478
+ * Once you have your API::Function object you can then call it the same way
479
+ * you would an API object.
480
+ *
481
+ * Example:
482
+ *
483
+ * require 'win32/api'
484
+ * include Win32
485
+ *
486
+ * LoadLibrary = API.new('LoadLibrary', 'P', 'L')
487
+ * GetProcAddress = API.new('GetProcAddress', 'LP', 'L')
488
+ *
489
+ * # Play a system beep
490
+ * hlib = LoadLibrary.call('user32')
491
+ * addr = GetProcAddress.call(hlib, 'MessageBeep')
492
+ * func = Win32::API::Function.new(addr, 'L', 'L')
493
+ * func.call(0)
494
+ */
495
+ static VALUE func_init(int argc, VALUE* argv, VALUE self){
496
+ Win32API* ptr;
497
+ int i;
498
+ VALUE v_address, v_proto, v_return;
499
+
500
+ rb_scan_args(argc, argv, "12", &v_address, &v_proto, &v_return);
501
+
502
+ Data_Get_Struct(self, Win32API, ptr);
503
+
504
+ // Convert a string prototype to an array of characters
505
+ if(rb_respond_to(v_proto, rb_intern("split")))
506
+ v_proto = rb_str_split(v_proto, "");
507
+
508
+ // Convert a nil or empty prototype to 'V' (void) automatically
509
+ if(NIL_P(v_proto) || RARRAY_LEN(v_proto) == 0){
510
+ v_proto = rb_ary_new();
511
+ rb_ary_push(v_proto, rb_str_new2("V"));
512
+ }
513
+
514
+ // Set an arbitrary limit of 20 parameters
515
+ if(20 < RARRAY_LEN(v_proto))
516
+ rb_raise(rb_eArgError, "too many parameters: %li\n", RARRAY_LEN(v_proto));
517
+
518
+ // Set the default return type to 'L' (DWORD)
519
+ if(NIL_P(v_return))
520
+ v_return = rb_str_new2("L");
521
+
522
+ ptr->function = (FARPROC)NUM2SIZET(v_address);
523
+
524
+ // Push the numeric prototypes onto our int array for later use.
525
+
526
+ for(i = 0; i < RARRAY_LEN(v_proto); i++){
527
+ #if defined TAINTING_SUPPORT
528
+ SafeStringValue(RARRAY_PTR(v_proto)[i]);
529
+ #endif
530
+ switch(*(char*)StringValuePtr(RARRAY_PTR(v_proto)[i])){
531
+ case 'L':
532
+ ptr->prototype[i] = _T_LONG;
533
+ break;
534
+ case 'P':
535
+ ptr->prototype[i] = _T_POINTER;
536
+ break;
537
+ case 'I': case 'B':
538
+ ptr->prototype[i] = _T_INTEGER;
539
+ break;
540
+ case 'V':
541
+ ptr->prototype[i] = _T_VOID;
542
+ break;
543
+ case 'K':
544
+ ptr->prototype[i] = _T_CALLBACK;
545
+ break;
546
+ case 'S':
547
+ ptr->prototype[i] = _T_STRING;
548
+ break;
549
+ default:
550
+ rb_raise(cAPIProtoError, "Illegal prototype '%s'",
551
+ StringValuePtr(RARRAY_PTR(v_proto)[i])
552
+ );
553
+ }
554
+ }
555
+
556
+ // Store the return type for later use.
557
+
558
+ // Automatically convert empty strings or nil to type void.
559
+ if(NIL_P(v_return) || RSTRING_LEN(v_return) == 0){
560
+ v_return = rb_str_new2("V");
561
+ ptr->return_type = _T_VOID;
562
+ }
563
+ else{
564
+ #if defined TAINTING_SUPPORT
565
+ SafeStringValue(v_return);
566
+ #endif
567
+ switch(*RSTRING_PTR(v_return)){
568
+ case 'L':
569
+ ptr->return_type = _T_LONG;
570
+ break;
571
+ case 'P':
572
+ ptr->return_type = _T_POINTER;
573
+ break;
574
+ case 'I': case 'B':
575
+ ptr->return_type = _T_INTEGER;
576
+ break;
577
+ case 'V':
578
+ ptr->return_type = _T_VOID;
579
+ break;
580
+ case 'S':
581
+ ptr->return_type = _T_STRING;
582
+ break;
583
+ default:
584
+ rb_raise(cAPIProtoError, "Illegal return type '%s'",
585
+ RSTRING_PTR(v_return)
586
+ );
587
+ }
588
+ }
589
+
590
+ rb_iv_set(self, "@address", v_address);
591
+ rb_iv_set(self, "@prototype", v_proto);
592
+ rb_iv_set(self, "@return_type", v_return);
593
+
594
+ return self;
595
+ }
596
+
597
+ typedef struct {
598
+ uintptr_t params[20];
599
+ } CALLPARAM;
600
+
601
+
602
+ DWORD CallbackFunction(CALLPARAM param, VALUE callback)
603
+ {
604
+ VALUE v_proto, v_return, v_proc, v_retval;
605
+ VALUE argv[20];
606
+ int i, argc;
607
+ char *a_proto;
608
+ char *a_return;
609
+
610
+ if(callback && !NIL_P(callback)){
611
+ v_proto = rb_iv_get(callback, "@prototype");
612
+ a_proto = RSTRING_PTR(v_proto);
613
+
614
+ v_return = rb_iv_get(callback, "@return_type");
615
+ a_return = RSTRING_PTR(v_return);
616
+
617
+ v_proc = rb_iv_get(callback, "@function");
618
+ argc = RSTRING_LEN(v_proto);
619
+
620
+ for(i=0; i < RSTRING_LEN(v_proto); i++){
621
+ argv[i] = Qnil;
622
+ switch(a_proto[i]){
623
+ case 'L':
624
+ argv[i] = SIZET2NUM(param.params[i]);
625
+ break;
626
+ case 'P':
627
+ if(param.params[i])
628
+ argv[i] = rb_str_new2((char *)param.params[i]);
629
+ break;
630
+ case 'I':
631
+ argv[i] = INT2NUM(param.params[i]);
632
+ break;
633
+ default:
634
+ rb_raise(cAPIProtoError, "Illegal prototype '%c'", a_proto[i]);
635
+ }
636
+ }
637
+
638
+ v_retval = rb_funcall2(v_proc, rb_intern("call"), argc, argv);
639
+
640
+ /* Handle true and false explicitly, as some CALLBACK functions
641
+ * require TRUE or FALSE to break out of loops, etc.
642
+ */
643
+ if(v_retval == Qtrue)
644
+ return TRUE;
645
+ else if(v_retval == Qfalse)
646
+ return FALSE;
647
+
648
+ switch (*a_return) {
649
+ case 'I':
650
+ return NUM2INT(v_retval);
651
+ break;
652
+ case 'L':
653
+ return NUM2SIZET(v_retval);
654
+ break;
655
+ case 'S':
656
+ return (uintptr_t)RSTRING_PTR(v_retval);
657
+ break;
658
+ case 'P':
659
+ if(NIL_P(v_retval)){
660
+ return 0;
661
+ }
662
+ else if(FIXNUM_P(v_retval)){
663
+ return NUM2SIZET(v_retval);
664
+ }
665
+ else{
666
+ StringValue(v_retval);
667
+ rb_str_modify(v_retval);
668
+ return (uintptr_t)StringValuePtr(v_retval);
669
+ }
670
+ break;
671
+ }
672
+ }
673
+
674
+ return 0;
675
+ }
676
+
677
+ #define CALLBACK0(x) DWORD CALLBACK CallbackFunction0_##x() {\
678
+ CALLPARAM param = {{0}};\
679
+ param.params[0] = 0;\
680
+ return CallbackFunction(param,FuncTable[0][x]);\
681
+ }
682
+
683
+ #define CALLBACK1(x) DWORD CALLBACK CallbackFunction1_##x(DWORD p1) {\
684
+ CALLPARAM param = {{p1}};\
685
+ return CallbackFunction(param,FuncTable[1][x]);\
686
+ }
687
+
688
+ #define CALLBACK2(x) DWORD CALLBACK CallbackFunction2_##x(\
689
+ DWORD p1, DWORD p2){\
690
+ CALLPARAM param = {{p1,p2}};\
691
+ return CallbackFunction(param,FuncTable[2][x]);\
692
+ }
693
+
694
+ #define CALLBACK3(x) DWORD CALLBACK CallbackFunction3_##x(\
695
+ DWORD p1, DWORD p2, DWORD p3){\
696
+ CALLPARAM param = {{p1,p2,p3}};\
697
+ return CallbackFunction(param,FuncTable[3][x]);\
698
+ }
699
+
700
+ #define CALLBACK4(x) DWORD CALLBACK CallbackFunction4_##x(\
701
+ DWORD p1, DWORD p2, DWORD p3, DWORD p4){\
702
+ CALLPARAM param = {{p1,p2,p3,p4}};\
703
+ return CallbackFunction(param,FuncTable[4][x]);\
704
+ }
705
+
706
+ #define CALLBACK5(x) DWORD CALLBACK CallbackFunction5_##x(\
707
+ DWORD p1, DWORD p2, DWORD p3, DWORD p4, DWORD p5\
708
+ ){\
709
+ CALLPARAM param = {{p1,p2,p3,p4,p5}};\
710
+ return CallbackFunction(param,FuncTable[5][x]);\
711
+ }
712
+
713
+ #define CALLBACK6(x) DWORD CALLBACK CallbackFunction6_##x(\
714
+ DWORD p1, DWORD p2, DWORD p3, DWORD p4, DWORD p5, DWORD p6\
715
+ ){\
716
+ CALLPARAM param = {{p1,p2,p3,p4,p5,p6}};\
717
+ return CallbackFunction(param,FuncTable[6][x]);\
718
+ }
719
+
720
+ #define CALLBACK7(x) DWORD CALLBACK CallbackFunction7_##x(\
721
+ DWORD p1, DWORD p2, DWORD p3, DWORD p4, DWORD p5, DWORD p6, DWORD p7\
722
+ ){\
723
+ CALLPARAM param = {{p1,p2,p3,p4,p5,p6,p7}};\
724
+ return CallbackFunction(param,FuncTable[7][x]);\
725
+ }
726
+
727
+ #define CALLBACK8(x) DWORD CALLBACK CallbackFunction8_##x(\
728
+ DWORD p1, DWORD p2, DWORD p3, DWORD p4,\
729
+ DWORD p5, DWORD p6, DWORD p7, DWORD p8\
730
+ ){\
731
+ CALLPARAM param = {{p1,p2,p3,p4,p5,p6,p7,p8}};\
732
+ return CallbackFunction(param,FuncTable[8][x]);\
733
+ }
734
+
735
+ #define CALLBACK9(x) DWORD CALLBACK CallbackFunction9_##x(\
736
+ DWORD p1, DWORD p2, DWORD p3, DWORD p4, DWORD p5,\
737
+ DWORD p6, DWORD p7, DWORD p8, DWORD p9\
738
+ ){\
739
+ CALLPARAM param = {{p1,p2,p3,p4,p5,p6,p7,p8,p9}};\
740
+ return CallbackFunction(param,FuncTable[9][x]);\
741
+ }
742
+
743
+ #define DEFCALLBACK(x) CALLBACK##x(0)\
744
+ CALLBACK##x(1)\
745
+ CALLBACK##x(2)\
746
+ CALLBACK##x(3)\
747
+ CALLBACK##x(4)\
748
+ CALLBACK##x(5)\
749
+ CALLBACK##x(6)\
750
+ CALLBACK##x(7)\
751
+ CALLBACK##x(8)\
752
+ CALLBACK##x(9)
753
+
754
+ #define CF(x,y) CallbackFunction##x##_##y
755
+
756
+ static VALUE FuncTable[10][10];
757
+
758
+ DEFCALLBACK(0)
759
+ DEFCALLBACK(1)
760
+ DEFCALLBACK(2)
761
+ DEFCALLBACK(3)
762
+ DEFCALLBACK(4)
763
+ DEFCALLBACK(5)
764
+ DEFCALLBACK(6)
765
+ DEFCALLBACK(7)
766
+ DEFCALLBACK(8)
767
+ DEFCALLBACK(9)
768
+
769
+ void *CallbackTable[10][10] = {
770
+ {CF(0,0),CF(0,1),CF(0,2),CF(0,3),CF(0,4),CF(0,5),CF(0,6),CF(0,7),CF(0,8),CF(0,9)},
771
+ {CF(1,0),CF(1,1),CF(1,2),CF(1,3),CF(1,4),CF(1,5),CF(1,6),CF(1,7),CF(1,8),CF(1,9)},
772
+ {CF(2,0),CF(2,1),CF(2,2),CF(2,3),CF(2,4),CF(2,5),CF(2,6),CF(2,7),CF(2,8),CF(2,9)},
773
+ {CF(3,0),CF(3,1),CF(3,2),CF(3,3),CF(3,4),CF(3,5),CF(3,6),CF(3,7),CF(3,8),CF(3,9)},
774
+ {CF(4,0),CF(4,1),CF(4,2),CF(4,3),CF(4,4),CF(4,5),CF(4,6),CF(4,7),CF(4,8),CF(4,9)},
775
+ {CF(5,0),CF(5,1),CF(5,2),CF(5,3),CF(5,4),CF(5,5),CF(5,6),CF(5,7),CF(5,8),CF(5,9)},
776
+ {CF(6,0),CF(6,1),CF(6,2),CF(6,3),CF(6,4),CF(6,5),CF(6,6),CF(6,7),CF(6,8),CF(6,9)},
777
+ {CF(7,0),CF(7,1),CF(7,2),CF(7,3),CF(7,4),CF(7,5),CF(7,6),CF(7,7),CF(7,8),CF(7,9)},
778
+ {CF(8,0),CF(8,1),CF(8,2),CF(8,3),CF(8,4),CF(8,5),CF(8,6),CF(8,7),CF(8,8),CF(8,9)},
779
+ {CF(9,0),CF(9,1),CF(9,2),CF(9,3),CF(9,4),CF(9,5),CF(9,6),CF(9,7),CF(9,8),CF(9,9)}};
780
+
781
+
782
+ void *find_callback(VALUE obj,int len)
783
+ {
784
+ int i;
785
+ for(i=0;i<10;i++)
786
+ {
787
+ if(FuncTable[len][i]==0)
788
+ break;
789
+ }
790
+ if(i>=10)
791
+ rb_raise(cAPIError,"too many callbacks are defined.");
792
+ FuncTable[len][i] = obj;
793
+ return CallbackTable[len][i];
794
+ }
795
+
796
+ /*
797
+ * call-seq:
798
+ * Win32::API#call(arg1, arg2, ...)
799
+ *
800
+ * Calls the function pointer with the given arguments (if any). Note that,
801
+ * while this method will catch some prototype mismatches (raising a TypeError
802
+ * in the process), it is not fulproof. It is ultimately your job to make
803
+ * sure the arguments match the +prototype+ specified in the constructor.
804
+ *
805
+ * For convenience, nil is converted to NULL, true is converted to TRUE (1)
806
+ * and false is converted to FALSE (0).
807
+ */
808
+ static VALUE api_call(int argc, VALUE* argv, VALUE self){
809
+ VALUE v_proto, v_args, v_arg, v_return;
810
+ Win32API* ptr;
811
+ uintptr_t return_value;
812
+ int i = 0;
813
+ int len;
814
+ ThreadData* thread_data = thread_data_get();
815
+
816
+ struct{
817
+ uintptr_t params[20];
818
+ } param;
819
+
820
+ Data_Get_Struct(self, Win32API, ptr);
821
+
822
+ rb_scan_args(argc, argv, "0*", &v_args);
823
+
824
+ v_proto = rb_iv_get(self, "@prototype");
825
+
826
+ // For void prototypes, allow either no args or an explicit nil
827
+ if(RARRAY_LEN(v_proto) != RARRAY_LEN(v_args)){
828
+ char* c = StringValuePtr(RARRAY_PTR(v_proto)[0]);
829
+ if(!strcmp(c, "V")){
830
+ rb_ary_push(v_args, Qnil);
831
+ }
832
+ else{
833
+ rb_raise(rb_eArgError,
834
+ "wrong number of parameters: expected %ld, got %ld",
835
+ RARRAY_LEN(v_proto), RARRAY_LEN(v_args)
836
+ );
837
+ }
838
+ }
839
+
840
+ len = RARRAY_LEN(v_proto);
841
+
842
+ for(i = 0; i < len; i++){
843
+ v_arg = RARRAY_PTR(v_args)[i];
844
+
845
+ // Convert nil to NULL. Otherwise convert as appropriate.
846
+ if(NIL_P(v_arg))
847
+ param.params[i] = (uintptr_t)NULL;
848
+ else if(v_arg == Qtrue)
849
+ param.params[i] = TRUE;
850
+ else if(v_arg == Qfalse)
851
+ param.params[i] = FALSE;
852
+ else
853
+ switch(ptr->prototype[i]){
854
+ case _T_LONG:
855
+ param.params[i] = NUM2SIZET(v_arg);
856
+ break;
857
+ case _T_INTEGER:
858
+ param.params[i] = NUM2INT(v_arg);
859
+ break;
860
+ case _T_POINTER:
861
+ if(FIXNUM_P(v_arg)){
862
+ param.params[i] = NUM2SIZET(v_arg);
863
+ }
864
+ else{
865
+ StringValue(v_arg);
866
+ rb_str_modify(v_arg);
867
+ param.params[i] = (uintptr_t)StringValuePtr(v_arg);
868
+ }
869
+ break;
870
+ case _T_CALLBACK:
871
+ ActiveCallback = v_arg;
872
+ param.params[i] = (LPARAM)NUM2SIZET(rb_iv_get(ActiveCallback, "@address"));;
873
+ break;
874
+ case _T_STRING:
875
+ param.params[i] = (uintptr_t)RSTRING_PTR(v_arg);
876
+ break;
877
+ default:
878
+ param.params[i] = NUM2SIZET(v_arg);
879
+ }
880
+ }
881
+
882
+ /* Call the function, get the return value */
883
+ if(strcmp(StringValuePtr(RARRAY_PTR(v_proto)[0]), "V") == 0 && len == 1)
884
+ {
885
+ return_value = ptr->function();
886
+ }
887
+ else
888
+ {
889
+ switch(len)
890
+ {
891
+ case 0:
892
+ return_value = ptr->function();
893
+ break;
894
+ case 1:
895
+ return_value = ptr->function(param.params[0]);
896
+ break;
897
+ case 2:
898
+ return_value = ptr->function(param.params[0], param.params[1]);
899
+ break;
900
+ case 3:
901
+ return_value = ptr->function(param.params[0], param.params[1],
902
+ param.params[2]);
903
+ break;
904
+ case 4:
905
+ return_value = ptr->function(param.params[0], param.params[1],
906
+ param.params[2], param.params[3]);
907
+ break;
908
+ case 5:
909
+ return_value = ptr->function(param.params[0], param.params[1],
910
+ param.params[2], param.params[3], param.params[4]);
911
+ break;
912
+ case 6:
913
+ return_value = ptr->function(param.params[0], param.params[1],
914
+ param.params[2], param.params[3], param.params[4], param.params[5]);
915
+ break;
916
+ case 7:
917
+ return_value = ptr->function(param.params[0], param.params[1],
918
+ param.params[2], param.params[3], param.params[4], param.params[5],
919
+ param.params[6]);
920
+ break;
921
+ case 8:
922
+ return_value = ptr->function(param.params[0], param.params[1],
923
+ param.params[2], param.params[3], param.params[4], param.params[5],
924
+ param.params[6], param.params[7]);
925
+ break;
926
+ case 9:
927
+ return_value = ptr->function(param.params[0], param.params[1],
928
+ param.params[2], param.params[3], param.params[4], param.params[5],
929
+ param.params[6], param.params[7], param.params[8]);
930
+ break;
931
+ case 10:
932
+ return_value = ptr->function(param.params[0], param.params[1],
933
+ param.params[2], param.params[3], param.params[4], param.params[5],
934
+ param.params[6], param.params[7], param.params[8], param.params[9]);
935
+ break;
936
+ case 11:
937
+ return_value = ptr->function(param.params[0], param.params[1],
938
+ param.params[2], param.params[3], param.params[4], param.params[5],
939
+ param.params[6], param.params[7], param.params[8], param.params[9],
940
+ param.params[10]);
941
+ break;
942
+ case 12:
943
+ return_value = ptr->function(param.params[0], param.params[1],
944
+ param.params[2], param.params[3], param.params[4], param.params[5],
945
+ param.params[6], param.params[7], param.params[8], param.params[9],
946
+ param.params[10], param.params[11]);
947
+ break;
948
+ case 13:
949
+ return_value = ptr->function(param.params[0], param.params[1],
950
+ param.params[2], param.params[3], param.params[4], param.params[5],
951
+ param.params[6], param.params[7], param.params[8], param.params[9],
952
+ param.params[10], param.params[11], param.params[12]);
953
+ break;
954
+ case 14:
955
+ return_value = ptr->function(param.params[0], param.params[1],
956
+ param.params[2], param.params[3], param.params[4], param.params[5],
957
+ param.params[6], param.params[7], param.params[8], param.params[9],
958
+ param.params[10], param.params[11], param.params[12], param.params[13]);
959
+ break;
960
+ case 15:
961
+ return_value = ptr->function(param.params[0], param.params[1],
962
+ param.params[2], param.params[3], param.params[4], param.params[5],
963
+ param.params[6], param.params[7], param.params[8], param.params[9],
964
+ param.params[10], param.params[11], param.params[12], param.params[13],
965
+ param.params[14]);
966
+ break;
967
+ case 16:
968
+ return_value = ptr->function(param.params[0], param.params[1],
969
+ param.params[2], param.params[3], param.params[4], param.params[5],
970
+ param.params[6], param.params[7], param.params[8], param.params[9],
971
+ param.params[10], param.params[11], param.params[12], param.params[13],
972
+ param.params[14], param.params[15]);
973
+ break;
974
+ case 17:
975
+ return_value = ptr->function(param.params[0], param.params[1],
976
+ param.params[2], param.params[3], param.params[4], param.params[5],
977
+ param.params[6], param.params[7], param.params[8], param.params[9],
978
+ param.params[10], param.params[11], param.params[12], param.params[13],
979
+ param.params[14], param.params[15], param.params[16]);
980
+ break;
981
+ case 18:
982
+ return_value = ptr->function(param.params[0], param.params[1],
983
+ param.params[2], param.params[3], param.params[4], param.params[5],
984
+ param.params[6], param.params[7], param.params[8], param.params[9],
985
+ param.params[10], param.params[11], param.params[12], param.params[13],
986
+ param.params[14], param.params[15], param.params[16], param.params[17]);
987
+ break;
988
+ case 19:
989
+ return_value = ptr->function(param.params[0], param.params[1],
990
+ param.params[2], param.params[3], param.params[4], param.params[5],
991
+ param.params[6], param.params[7], param.params[8], param.params[9],
992
+ param.params[10], param.params[11], param.params[12], param.params[13],
993
+ param.params[14], param.params[15], param.params[16], param.params[17],
994
+ param.params[18]);
995
+ break;
996
+ case 20:
997
+ return_value = ptr->function(param.params[0], param.params[1],
998
+ param.params[2], param.params[3], param.params[4], param.params[5],
999
+ param.params[6], param.params[7], param.params[8], param.params[9],
1000
+ param.params[10], param.params[11], param.params[12], param.params[13],
1001
+ param.params[14], param.params[15], param.params[16], param.params[17],
1002
+ param.params[18], param.params[19]);
1003
+ break;
1004
+ default:
1005
+ rb_raise(rb_eArgError,"number of parameters exceed 20!");
1006
+ }
1007
+ }
1008
+
1009
+ thread_data->win32api_error = GetLastError();
1010
+
1011
+ /* Return the appropriate type based on the return type specified
1012
+ * in the constructor.
1013
+ */
1014
+ switch(ptr->return_type){
1015
+ case _T_INTEGER:
1016
+ v_return = INT2NUM(return_value);
1017
+ break;
1018
+ case _T_LONG:
1019
+ v_return = SIZET2NUM(return_value);
1020
+ break;
1021
+ case _T_VOID:
1022
+ v_return = Qnil;
1023
+ break;
1024
+ case _T_POINTER:
1025
+ if(!return_value){
1026
+ v_return = Qnil;
1027
+ }
1028
+ else{
1029
+ VALUE v_efunc = rb_iv_get(self, "@effective_function_name");
1030
+ char* efunc = RSTRING_PTR(v_efunc);
1031
+ if(efunc[strlen(efunc)-1] == 'W'){
1032
+ v_return = rb_str_new(
1033
+ (TCHAR*)return_value,
1034
+ wcslen((wchar_t*)return_value)*2
1035
+ );
1036
+ }
1037
+ else{
1038
+ v_return = rb_str_new2((TCHAR*)return_value);
1039
+ }
1040
+ }
1041
+ break;
1042
+ case _T_STRING:
1043
+ {
1044
+ VALUE v_efunc = rb_iv_get(self, "@effective_function_name");
1045
+ char* efunc = RSTRING_PTR(v_efunc);
1046
+
1047
+ if(efunc[strlen(efunc)-1] == 'W'){
1048
+ v_return = rb_str_new(
1049
+ (TCHAR*)return_value,
1050
+ wcslen((wchar_t*)return_value)*2
1051
+ );
1052
+ }
1053
+ else{
1054
+ v_return = rb_str_new2((TCHAR*)return_value);
1055
+ }
1056
+ }
1057
+ break;
1058
+ default:
1059
+ v_return = INT2NUM(0);
1060
+ }
1061
+
1062
+ return v_return;
1063
+ }
1064
+
1065
+ /*
1066
+ * call-seq:
1067
+ * Win32::API.last_error
1068
+ *
1069
+ * Return the last Win32 error code of the current executing thread.
1070
+ *
1071
+ * The error code shouldn't be retrieved by calling GetLastError() manually
1072
+ * because Ruby's internal code may call other Win32 API and reset the error
1073
+ * code before it.
1074
+ */
1075
+ static VALUE get_last_error(VALUE self)
1076
+ {
1077
+ return ULONG2NUM(thread_data_get()->win32api_error);
1078
+ }
1079
+
1080
+ /*
1081
+ * Wraps the Windows API functions in a Ruby interface.
1082
+ */
1083
+ void Init_api(){
1084
+ VALUE mWin32, cAPI, cCallback, cFunction;
1085
+
1086
+ /* Modules and Classes */
1087
+
1088
+ /* The Win32 module serves as a namespace only */
1089
+ mWin32 = rb_define_module("Win32");
1090
+
1091
+ /* The API class encapsulates a function pointer to Windows API function */
1092
+ cAPI = rb_define_class_under(mWin32, "API", rb_cObject);
1093
+
1094
+ /* The API::Callback class encapsulates a Windows CALLBACK function */
1095
+ cCallback = rb_define_class_under(cAPI, "Callback", rb_cObject);
1096
+
1097
+ /* The API::Function class encapsulates a raw function pointer */
1098
+ cFunction = rb_define_class_under(cAPI, "Function", cAPI);
1099
+
1100
+ /* The API::Error class serves as a base class for other errors */
1101
+ cAPIError = rb_define_class_under(cAPI, "Error", rb_eRuntimeError);
1102
+
1103
+ /* The LoadError class is raised if a function cannot be found or loaded */
1104
+ cAPILoadError = rb_define_class_under(cAPI, "LoadLibraryError", cAPIError);
1105
+
1106
+ /* The PrototypeError class is raised if an invalid prototype is passed */
1107
+ cAPIProtoError = rb_define_class_under(cAPI, "PrototypeError", cAPIError);
1108
+
1109
+ /* Miscellaneous */
1110
+ rb_define_alloc_func(cAPI, api_allocate);
1111
+
1112
+ /* GetLastError alternative */
1113
+ rb_define_singleton_method(cAPI, "last_error", get_last_error, 0);
1114
+
1115
+ /* Win32::API Instance Methods */
1116
+ rb_define_method(cAPI, "initialize", api_init, -1);
1117
+ rb_define_method(cAPI, "call", api_call, -1);
1118
+
1119
+ /* Win32::API::Callback Instance Methods */
1120
+ rb_define_method(cCallback, "initialize", callback_init, -1);
1121
+
1122
+ /* Win32::API::Function Instance Methods */
1123
+ rb_define_method(cFunction, "initialize", func_init, -1);
1124
+
1125
+ /* The name of the DLL that exports the API function */
1126
+ rb_define_attr(cAPI, "dll_name", 1, 0);
1127
+
1128
+ /* The name of the function passed to the constructor */
1129
+ rb_define_attr(cAPI, "function_name", 1, 0);
1130
+
1131
+ /* The name of the actual function that is returned by the constructor.
1132
+ * For example, if you passed 'GetUserName' to the constructor, then the
1133
+ * effective function name would be either 'GetUserNameA' or 'GetUserNameW'.
1134
+ */
1135
+ rb_define_attr(cAPI, "effective_function_name", 1, 0);
1136
+
1137
+ /* The prototype, returned as an array of characters */
1138
+ rb_define_attr(cAPI, "prototype", 1, 0);
1139
+
1140
+ /* The return type, returned as a single character, S, P, L, I, V or B */
1141
+ rb_define_attr(cAPI, "return_type", 1, 0);
1142
+
1143
+ /* Win32::API::Callback Instance Methods */
1144
+
1145
+ /* The prototype, returned as an array of characters */
1146
+ rb_define_attr(cCallback, "prototype", 1, 0);
1147
+
1148
+ /* The return type, returned as a single character, S, P, L, I, V or B */
1149
+ rb_define_attr(cCallback, "return_type", 1, 0);
1150
+
1151
+ /* The numeric address of the function pointer */
1152
+ rb_define_attr(cCallback, "address", 1, 0);
1153
+ rb_define_attr(cFunction, "address", 1, 0);
1154
+
1155
+ /* Constants */
1156
+
1157
+ /* 1.6.0: The version of the win32-api library */
1158
+ rb_define_const(cAPI, "VERSION", rb_str_new2(WINDOWS_API_VERSION));
1159
+ }