]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/cgo/internal/test/test.go
9a6c6d82cefa1abfde6c3a2dcc03d1ed08a6f479
[gostls13.git] / src / cmd / cgo / internal / test / test.go
1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Test cases for cgo.
6 // Both the import "C" prologue and the main file are sorted by issue number.
7 // This file contains C definitions (not just declarations)
8 // and so it must NOT contain any //export directives on Go functions.
9 // See testx.go for exports.
10
11 package cgotest
12
13 /*
14 #include <complex.h>
15 #include <math.h>
16 #include <stdarg.h>
17 #include <stdbool.h>
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <sys/stat.h>
25 #include <errno.h>
26 #cgo !darwin LDFLAGS: -lm
27
28 #ifndef WIN32
29 #include <pthread.h>
30 #include <signal.h>
31 #endif
32
33 // alignment tests
34
35 typedef unsigned char Uint8;
36 typedef unsigned short Uint16;
37
38 typedef enum {
39  MOD1 = 0x0000,
40  MODX = 0x8000
41 } SDLMod;
42
43 typedef enum {
44  A1 = 1,
45  B1 = 322,
46  SDLK_LAST
47 } SDLKey;
48
49 typedef struct SDL_keysym {
50         Uint8 scancode;
51         SDLKey sym;
52         SDLMod mod;
53         Uint16 unicode;
54 } SDL_keysym;
55
56 typedef struct SDL_KeyboardEvent {
57         Uint8 typ;
58         Uint8 which;
59         Uint8 state;
60         SDL_keysym keysym;
61 } SDL_KeyboardEvent;
62
63 void makeEvent(SDL_KeyboardEvent *event) {
64  unsigned char *p;
65  int i;
66
67  p = (unsigned char*)event;
68  for (i=0; i<sizeof *event; i++) {
69    p[i] = i;
70  }
71 }
72
73 int same(SDL_KeyboardEvent* e, Uint8 typ, Uint8 which, Uint8 state, Uint8 scan, SDLKey sym, SDLMod mod, Uint16 uni) {
74   return e->typ == typ && e->which == which && e->state == state && e->keysym.scancode == scan && e->keysym.sym == sym && e->keysym.mod == mod && e->keysym.unicode == uni;
75 }
76
77 void cTest(SDL_KeyboardEvent *event) {
78  printf("C: %#x %#x %#x %#x %#x %#x %#x\n", event->typ, event->which, event->state,
79    event->keysym.scancode, event->keysym.sym, event->keysym.mod, event->keysym.unicode);
80  fflush(stdout);
81 }
82
83 // api
84
85 const char *greeting = "hello, world";
86
87 // basic test cases
88
89 #define SHIFT(x, y)  ((x)<<(y))
90 #define KILO SHIFT(1, 10)
91 #define UINT32VAL 0xc008427bU
92
93 enum E {
94         Enum1 = 1,
95         Enum2 = 2,
96 };
97
98 typedef unsigned char cgo_uuid_t[20];
99
100 void uuid_generate(cgo_uuid_t x) {
101         x[0] = 0;
102 }
103
104 struct S {
105         int x;
106 };
107
108 const char *cstr = "abcefghijklmnopqrstuvwxyzABCEFGHIJKLMNOPQRSTUVWXYZ1234567890";
109
110 extern enum E myConstFunc(struct S* const ctx, int const id, struct S **const filter);
111
112 enum E myConstFunc(struct S *const ctx, int const id, struct S **const filter) { return 0; }
113
114 int add(int x, int y) {
115         return x+y;
116 };
117
118 // escape vs noescape
119
120 #cgo noescape handleGoStringPointerNoescape
121 void handleGoStringPointerNoescape(void *s) {}
122
123 void handleGoStringPointerEscape(void *s) {}
124
125 // Following mimics vulkan complex definitions for benchmarking cgocheck overhead.
126
127 typedef uint32_t VkFlags;
128 typedef VkFlags  VkDeviceQueueCreateFlags;
129 typedef uint32_t VkStructureType;
130
131 typedef struct VkDeviceQueueCreateInfo {
132     VkStructureType             sType;
133     const void*                 pNext;
134     VkDeviceQueueCreateFlags    flags;
135     uint32_t                    queueFamilyIndex;
136     uint32_t                    queueCount;
137     const float*                pQueuePriorities;
138 } VkDeviceQueueCreateInfo;
139
140 typedef struct VkPhysicalDeviceFeatures {
141     uint32_t bools[56];
142 } VkPhysicalDeviceFeatures;
143
144 typedef struct VkDeviceCreateInfo {
145     VkStructureType                    sType;
146     const void*                        pNext;
147     VkFlags                            flags;
148     uint32_t                           queueCreateInfoCount;
149     const VkDeviceQueueCreateInfo*     pQueueCreateInfos;
150     uint32_t                           enabledLayerCount;
151     const char* const*                 ppEnabledLayerNames;
152     uint32_t                           enabledExtensionCount;
153     const char* const*                 ppEnabledExtensionNames;
154     const VkPhysicalDeviceFeatures*    pEnabledFeatures;
155 } VkDeviceCreateInfo;
156
157 void handleComplexPointer(VkDeviceCreateInfo *a0) {}
158 void handleComplexPointer8(
159         VkDeviceCreateInfo *a0, VkDeviceCreateInfo *a1, VkDeviceCreateInfo *a2, VkDeviceCreateInfo *a3,
160         VkDeviceCreateInfo *a4, VkDeviceCreateInfo *a5, VkDeviceCreateInfo *a6, VkDeviceCreateInfo *a7
161 ) {}
162
163 // complex alignment
164
165 struct {
166         float x;
167         _Complex float y;
168 } cplxAlign = { 3.14, 2.17 };
169
170 // constants and pointer checking
171
172 #define CheckConstVal 0
173
174 typedef struct {
175         int *p;
176 } CheckConstStruct;
177
178 static void CheckConstFunc(CheckConstStruct *p, int e) {}
179
180 // duplicate symbol
181
182 int base_symbol = 0;
183 #define alias_one base_symbol
184 #define alias_two base_symbol
185
186 // function pointer variables
187
188 typedef int (*intFunc) ();
189
190 int
191 bridge_int_func(intFunc f)
192 {
193         return f();
194 }
195
196 int fortytwo()
197 {
198         return 42;
199 }
200
201 // issue 1222
202 typedef union {
203         long align;
204 } xxpthread_mutex_t;
205 struct ibv_async_event {
206         union {
207                 int x;
208         } element;
209 };
210 struct ibv_context {
211         xxpthread_mutex_t mutex;
212 };
213
214 // issue 1635
215 // Mac OS X's gcc will generate scattered relocation 2/1 for
216 // this function on Darwin/386, and 8l couldn't handle it.
217 // this example is in issue 1635
218 void scatter() {
219         void *p = scatter;
220         printf("scatter = %p\n", p);
221 }
222
223 // Adding this explicit extern declaration makes this a test for
224 // https://gcc.gnu.org/PR68072 aka https://golang.org/issue/13344 .
225 // It used to cause a cgo error when building with GCC 6.
226 extern int hola;
227
228 // this example is in issue 3253
229 int hola = 0;
230 int testHola() { return hola; }
231
232 // issue 3250
233 #ifdef WIN32
234 void testSendSIG() {}
235 #else
236 static void *thread(void *p) {
237         const int M = 100;
238         int i;
239         (void)p;
240         for (i = 0; i < M; i++) {
241                 pthread_kill(pthread_self(), SIGCHLD);
242                 usleep(rand() % 20 + 5);
243         }
244         return NULL;
245 }
246 void testSendSIG() {
247         const int N = 20;
248         int i;
249         pthread_t tid[N];
250         for (i = 0; i < N; i++) {
251                 usleep(rand() % 200 + 100);
252                 pthread_create(&tid[i], 0, thread, NULL);
253         }
254         for (i = 0; i < N; i++)
255                 pthread_join(tid[i], 0);
256 }
257 #endif
258
259 // issue 3261
260 // libgcc on ARM might be compiled as thumb code, but our 5l
261 // can't handle that, so we have to disable this test on arm.
262 #ifdef __ARMEL__
263 int vabs(int x) {
264         puts("testLibgcc is disabled on ARM because 5l cannot handle thumb library.");
265         return (x < 0) ? -x : x;
266 }
267 #elif defined(__arm64__) && defined(__clang__)
268 int vabs(int x) {
269         puts("testLibgcc is disabled on ARM64 with clang due to lack of libgcc.");
270         return (x < 0) ? -x : x;
271 }
272 #else
273 int __absvsi2(int); // dummy prototype for libgcc function
274 // we shouldn't name the function abs, as gcc might use
275 // the builtin one.
276 int vabs(int x) { return __absvsi2(x); }
277 #endif
278
279
280 // issue 3729
281 // access errno from void C function
282 const char _expA = 0x42;
283 const float _expB = 3.14159;
284 const short _expC = 0x55aa;
285 const int _expD = 0xdeadbeef;
286
287 #ifdef WIN32
288 void g(void) {}
289 void g2(int x, char a, float b, short c, int d) {}
290 #else
291
292 void g(void) {
293         errno = E2BIG;
294 }
295
296 // try to pass some non-trivial arguments to function g2
297 void g2(int x, char a, float b, short c, int d) {
298         if (a == _expA && b == _expB && c == _expC && d == _expD)
299                 errno = x;
300         else
301                 errno = -1;
302 }
303 #endif
304
305 // issue 3945
306 // Test that cgo reserves enough stack space during cgo call.
307 // See https://golang.org/issue/3945 for details.
308 void say() {
309         printf("%s from C\n", "hello");
310 }
311
312 // issue 4054 part 1 - other half in testx.go
313
314 typedef enum {
315         A = 0,
316         B,
317         C,
318         D,
319         E,
320         F,
321         G,
322         H,
323         II,
324         J,
325 } issue4054a;
326
327 // issue 4339
328 // We've historically permitted #include <>, so test it here.  Issue 29333.
329 // Also see issue 41059.
330 #include <issue4339.h>
331
332 // issue 4417
333 // cmd/cgo: bool alignment/padding issue.
334 // bool alignment is wrong and causing wrong arguments when calling functions.
335 static int c_bool(bool a, bool b, int c, bool d, bool e)  {
336    return c;
337 }
338
339 // issue 4857
340 #cgo CFLAGS: -Werror
341 const struct { int a; } *issue4857() { return (void *)0; }
342
343 // issue 5224
344 // Test that the #cgo CFLAGS directive works,
345 // with and without platform filters.
346 #cgo CFLAGS: -DCOMMON_VALUE=123
347 #cgo windows CFLAGS: -DIS_WINDOWS=1
348 #cgo !windows CFLAGS: -DIS_WINDOWS=0
349 int common = COMMON_VALUE;
350 int is_windows = IS_WINDOWS;
351
352 // issue 5227
353 // linker incorrectly treats common symbols and
354 // leaves them undefined.
355
356 typedef struct {
357         int Count;
358 } Fontinfo;
359
360 Fontinfo SansTypeface;
361
362 extern void init();
363
364 Fontinfo loadfont() {
365         Fontinfo f = {0};
366         return f;
367 }
368
369 void init() {
370         SansTypeface = loadfont();
371 }
372
373 // issue 5242
374 // Cgo incorrectly computed the alignment of structs
375 // with no Go accessible fields as 0, and then panicked on
376 // modulo-by-zero computations.
377
378 // issue 50987
379 // disable arm64 GCC warnings
380 #cgo CFLAGS: -Wno-psabi -Wno-unknown-warning-option
381
382 typedef struct {
383 } foo;
384
385 typedef struct {
386         int x : 1;
387 } bar;
388
389 int issue5242(foo f, bar b) {
390         return 5242;
391 }
392
393 // issue 5337
394 // Verify that we can withstand SIGPROF received on foreign threads
395
396 #ifdef WIN32
397 void test5337() {}
398 #else
399 static void *thread1(void *p) {
400         (void)p;
401         pthread_kill(pthread_self(), SIGPROF);
402         return NULL;
403 }
404 void test5337() {
405         pthread_t tid;
406         pthread_create(&tid, 0, thread1, NULL);
407         pthread_join(tid, 0);
408 }
409 #endif
410
411 // issue 5603
412
413 const long long issue5603exp = 0x12345678;
414 long long issue5603foo0() { return issue5603exp; }
415 long long issue5603foo1(void *p) { return issue5603exp; }
416 long long issue5603foo2(void *p, void *q) { return issue5603exp; }
417 long long issue5603foo3(void *p, void *q, void *r) { return issue5603exp; }
418 long long issue5603foo4(void *p, void *q, void *r, void *s) { return issue5603exp; }
419
420 // issue 5740
421
422 int test5740a(void), test5740b(void);
423
424 // issue 5986
425 static void output5986()
426 {
427     int current_row = 0, row_count = 0;
428     double sum_squares = 0;
429     double d;
430     do {
431         if (current_row == 10) {
432             current_row = 0;
433         }
434         ++row_count;
435     }
436     while (current_row++ != 1);
437     d =  sqrt(sum_squares / row_count);
438     printf("sqrt is: %g\n", d);
439 }
440
441 // issue 6128
442 // Test handling of #defined names in clang.
443 // NOTE: Must use hex, or else a shortcut for decimals
444 // in cgo avoids trying to pass this to clang.
445 #define X 0x1
446
447 // issue 6472
448 typedef struct
449 {
450         struct
451         {
452             int x;
453         } y[16];
454 } z;
455
456 // issue 6612
457 // Test new scheme for deciding whether C.name is an expression, type, constant.
458 // Clang silences some warnings when the name is a #defined macro, so test those too
459 // (even though we now use errors exclusively, not warnings).
460
461 void myfunc(void) {}
462 int myvar = 5;
463 const char *mytext = "abcdef";
464 typedef int mytype;
465 enum {
466         myenum = 1234,
467 };
468
469 #define myfunc_def myfunc
470 #define myvar_def myvar
471 #define mytext_def mytext
472 #define mytype_def mytype
473 #define myenum_def myenum
474 #define myint_def 12345
475 #define myfloat_def 1.5
476 #define mystring_def "hello"
477
478 // issue 6907
479 char* Issue6907CopyString(_GoString_ s) {
480         size_t n;
481         const char *p;
482         char *r;
483
484         n = _GoStringLen(s);
485         p = _GoStringPtr(s);
486         r = malloc(n + 1);
487         memmove(r, p, n);
488         r[n] = '\0';
489         return r;
490 }
491
492 // issue 7560
493 typedef struct {
494         char x;
495         long y;
496 } __attribute__((__packed__)) misaligned;
497
498 int
499 offset7560(void)
500 {
501         return (uintptr_t)&((misaligned*)0)->y;
502 }
503
504 // issue 7786
505 // No runtime test, just make sure that typedef and struct/union/class are interchangeable at compile time.
506
507 struct test7786;
508 typedef struct test7786 typedef_test7786;
509 void f7786(struct test7786 *ctx) {}
510 void g7786(typedef_test7786 *ctx) {}
511
512 typedef struct body7786 typedef_body7786;
513 struct body7786 { int x; };
514 void b7786(struct body7786 *ctx) {}
515 void c7786(typedef_body7786 *ctx) {}
516
517 typedef union union7786 typedef_union7786;
518 void u7786(union union7786 *ctx) {}
519 void v7786(typedef_union7786 *ctx) {}
520
521 // issue 8092
522 // Test that linker defined symbols (e.g., text, data) don't
523 // conflict with C symbols.
524 char text[] = "text";
525 char data[] = "data";
526 char *ctext(void) { return text; }
527 char *cdata(void) { return data; }
528
529 // issue 8428
530 // Cgo inconsistently translated zero size arrays.
531
532 struct issue8428one {
533         char b;
534         char rest[];
535 };
536
537 struct issue8428two {
538         void *p;
539         char b;
540         char rest[0];
541         char pad;
542 };
543
544 struct issue8428three {
545         char w[1][2][3][0];
546         char x[2][3][0][1];
547         char y[3][0][1][2];
548         char z[0][1][2][3];
549 };
550
551 // issue 8331 part 1 - part 2 in testx.go
552 // A typedef of an unnamed struct is the same struct when
553 // #include'd twice.  No runtime test; just make sure it compiles.
554 #include "issue8331.h"
555
556 // issue 8368 and 8441
557 // Recursive struct definitions didn't work.
558 // No runtime test; just make sure it compiles.
559 typedef struct one one;
560 typedef struct two two;
561 struct one {
562         two *x;
563 };
564 struct two {
565         one *x;
566 };
567
568 // issue 8811
569
570 extern int issue8811Initialized;
571 extern void issue8811Init();
572
573 void issue8811Execute() {
574         if(!issue8811Initialized)
575                 issue8811Init();
576 }
577
578 // issue 8945
579
580 typedef void (*PFunc8945)();
581 PFunc8945 func8945;
582
583 // issue 9557
584
585 struct issue9557_t {
586   int a;
587 } test9557bar = { 42 };
588 struct issue9557_t *issue9557foo = &test9557bar;
589
590 // issue 10303
591 // Pointers passed to C were not marked as escaping (bug in cgo).
592
593 typedef int *intptr;
594
595 void setintstar(int *x) {
596         *x = 1;
597 }
598
599 void setintptr(intptr x) {
600         *x = 1;
601 }
602
603 void setvoidptr(void *x) {
604         *(int*)x = 1;
605 }
606
607 typedef struct Struct Struct;
608 struct Struct {
609         int *P;
610 };
611
612 void setstruct(Struct s) {
613         *s.P = 1;
614 }
615
616 // issue 11925
617 // Structs with zero-length trailing fields are now padded by the Go compiler.
618
619 struct a11925 {
620         int i;
621         char a[0];
622         char b[0];
623 };
624
625 struct b11925 {
626         int i;
627         char a[0];
628         char b[];
629 };
630
631 // issue 12030
632 void issue12030conv(char *buf, double x) {
633         sprintf(buf, "d=%g", x);
634 }
635
636 // issue 14838
637
638 int check_cbytes(char *b, size_t l) {
639         int i;
640         for (i = 0; i < l; i++) {
641                 if (b[i] != i) {
642                         return 0;
643                 }
644         }
645         return 1;
646 }
647
648 // issue 17065
649 // Test that C symbols larger than a page play nicely with the race detector.
650 int ii[65537];
651
652 // issue 17537
653 // The void* cast introduced by cgo to avoid problems
654 // with const/volatile qualifiers breaks C preprocessor macros that
655 // emulate functions.
656
657 typedef struct {
658         int i;
659 } S17537;
660
661 int I17537(S17537 *p);
662
663 #define I17537(p) ((p)->i)
664
665 // Calling this function used to fail without the cast.
666 const int F17537(const char **p) {
667         return **p;
668 }
669
670 // issue 17723
671 // API compatibility checks
672
673 typedef char *cstring_pointer;
674 static void cstring_pointer_fun(cstring_pointer dummy) { }
675 const char *api_hello = "hello!";
676
677 // Calling this function used to trigger an error from the C compiler
678 // (issue 18298).
679 void F18298(const void *const *p) {
680 }
681
682 // Test that conversions between typedefs work as they used to.
683 typedef const void *T18298_1;
684 struct S18298 { int i; };
685 typedef const struct S18298 *T18298_2;
686 void G18298(T18298_1 t) {
687 }
688
689 // issue 18126
690 // cgo check of void function returning errno.
691 void Issue18126C(void **p) {}
692
693 // issue 18720
694
695 #define HELLO "hello"
696 #define WORLD "world"
697 #define HELLO_WORLD HELLO "\000" WORLD
698
699 struct foo { char c; };
700 #define SIZE_OF(x) sizeof(x)
701 #define SIZE_OF_FOO SIZE_OF(struct foo)
702 #define VAR1 VAR
703 #define VAR var
704 int var = 5;
705
706 #define ADDR &var
707
708 #define CALL fn()
709 int fn(void) {
710         return ++var;
711 }
712
713 // issue 20129
714
715 int issue20129 = 0;
716 typedef void issue20129Void;
717 issue20129Void issue20129Foo() {
718         issue20129 = 1;
719 }
720 typedef issue20129Void issue20129Void2;
721 issue20129Void2 issue20129Bar() {
722         issue20129 = 2;
723 }
724
725 // issue 20369
726 #define XUINT64_MAX        18446744073709551615ULL
727
728 // issue 21668
729 // Fail to guess the kind of the constant "x".
730 // No runtime test; just make sure it compiles.
731 const int x21668 = 42;
732
733 // issue 21708
734 #define CAST_TO_INT64 (int64_t)(-1)
735
736 // issue 21809
737 // Compile C `typedef` to go type aliases.
738
739 typedef long MySigned_t;
740 // tests alias-to-alias
741 typedef MySigned_t MySigned2_t;
742 long takes_long(long x) { return x * x; }
743 MySigned_t takes_typedef(MySigned_t x) { return x * x; }
744
745 // issue 22906
746
747 // It's going to be hard to include a whole real JVM to test this.
748 // So we'll simulate a really easy JVM using just the parts we need.
749 // This is the relevant part of jni.h.
750
751 struct _jobject;
752
753 typedef struct _jobject *jobject;
754 typedef jobject jclass;
755 typedef jobject jthrowable;
756 typedef jobject jstring;
757 typedef jobject jarray;
758 typedef jarray jbooleanArray;
759 typedef jarray jbyteArray;
760 typedef jarray jcharArray;
761 typedef jarray jshortArray;
762 typedef jarray jintArray;
763 typedef jarray jlongArray;
764 typedef jarray jfloatArray;
765 typedef jarray jdoubleArray;
766 typedef jarray jobjectArray;
767
768 typedef jobject jweak;
769
770 // Note: jvalue is already a non-pointer type due to it being a C union.
771
772 // issue 22958
773
774 typedef struct {
775         unsigned long long f8  : 8;
776         unsigned long long f16 : 16;
777         unsigned long long f24 : 24;
778         unsigned long long f32 : 32;
779         unsigned long long f40 : 40;
780         unsigned long long f48 : 48;
781         unsigned long long f56 : 56;
782         unsigned long long f64 : 64;
783 } issue22958Type;
784
785 // issue 23356
786 int a(void) { return 5; };
787 int r(void) { return 3; };
788
789 // issue 23720
790 typedef int *issue23720A;
791 typedef const int *issue23720B;
792 void issue23720F(issue23720B a) {}
793
794 // issue 24206
795 #if defined(__linux__) && defined(__x86_64__)
796 #include <sys/mman.h>
797 // Returns string with null byte at the last valid address
798 char* dangerousString1() {
799         int pageSize = 4096;
800         char *data = mmap(0, 2 * pageSize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, 0, 0);
801         mprotect(data + pageSize,pageSize,PROT_NONE);
802         int start = pageSize - 123 - 1; // last 123 bytes of first page + 1 null byte
803         int i = start;
804         for (; i < pageSize; i++) {
805         data[i] = 'x';
806         }
807         data[pageSize -1 ] = 0;
808         return data+start;
809 }
810
811 char* dangerousString2() {
812         int pageSize = 4096;
813         char *data = mmap(0, 3 * pageSize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, 0, 0);
814         mprotect(data + 2 * pageSize,pageSize,PROT_NONE);
815         int start = pageSize - 123 - 1; // last 123 bytes of first page + 1 null byte
816         int i = start;
817         for (; i < 2 * pageSize; i++) {
818         data[i] = 'x';
819         }
820         data[2*pageSize -1 ] = 0;
821         return data+start;
822 }
823 #else
824 char *dangerousString1() { return NULL; }
825 char *dangerousString2() { return NULL; }
826 #endif
827
828 // issue 26066
829 const unsigned long long int issue26066 = (const unsigned long long) -1;
830
831 // issue 26517
832 // Introduce two pointer types which are distinct, but have the same
833 // base type. Make sure that both of those pointer types get resolved
834 // correctly. Before the fix for 26517 if one of these pointer types
835 // was resolved before the other one was processed, the second one
836 // would never be resolved.
837 // Before this issue was fixed this test failed on Windows,
838 // where va_list expands to a named char* type.
839 typedef va_list TypeOne;
840 typedef char *TypeTwo;
841
842 // issue 28540
843
844 static void twoargs1(void *p, int n) {}
845 static void *twoargs2() { return 0; }
846 static int twoargs3(void * p) { return 0; }
847
848 // issue 28545
849 // Failed to add type conversion for negative constant.
850
851 static void issue28545F(char **p, int n, complex double a) {}
852
853 // issue 28772 part 1 - part 2 in testx.go
854 // Failed to add type conversion for Go constant set to C constant.
855 // No runtime test; just make sure it compiles.
856
857 #define issue28772Constant 1
858
859 // issue 28896
860 // cgo was incorrectly adding padding after a packed struct.
861 typedef struct {
862         void *f1;
863         uint32_t f2;
864 } __attribute__((__packed__)) innerPacked;
865
866 typedef struct {
867         innerPacked g1;
868         uint64_t g2;
869 } outerPacked;
870
871 typedef struct {
872         void *f1;
873         uint32_t f2;
874 } innerUnpacked;
875
876 typedef struct {
877         innerUnpacked g1;
878         uint64_t g2;
879 } outerUnpacked;
880
881 size_t offset(int x) {
882         switch (x) {
883         case 0:
884                 return offsetof(innerPacked, f2);
885         case 1:
886                 return offsetof(outerPacked, g2);
887         case 2:
888                 return offsetof(innerUnpacked, f2);
889         case 3:
890                 return offsetof(outerUnpacked, g2);
891         default:
892                 abort();
893         }
894 }
895
896 // issue 29748
897
898 typedef struct { char **p; } S29748;
899 static int f29748(S29748 *p) { return 0; }
900
901 // issue 29781
902 // Error with newline inserted into constant expression.
903 // Compilation test only, nothing to run.
904
905 static void issue29781F(char **p, int n) {}
906 #define ISSUE29781C 0
907
908 // issue 31093
909 static uint16_t issue31093F(uint16_t v) { return v; }
910
911 // issue 32579
912 typedef struct S32579 { unsigned char data[1]; } S32579;
913
914 // issue 37033, cgo.Handle
915 extern void GoFunc37033(uintptr_t handle);
916 void cFunc37033(uintptr_t handle) { GoFunc37033(handle); }
917
918 // issue 38649
919 // Test that #define'd type aliases work.
920 #define netbsd_gid unsigned int
921
922 // issue 40494
923 // Inconsistent handling of tagged enum and union types.
924 enum Enum40494 { X_40494 };
925 union Union40494 { int x; };
926 void issue40494(enum Enum40494 e, union Union40494* up) {}
927
928 // Issue 45451, bad handling of go:notinheap types.
929 typedef struct issue45451Undefined issue45451;
930
931 // Issue 49633, example of cgo.Handle with void*.
932 extern void GoFunc49633(void*);
933 void cfunc49633(void *context) { GoFunc49633(context); }
934
935 */
936 import "C"
937
938 import (
939         "context"
940         "fmt"
941         "math"
942         "math/rand"
943         "os"
944         "os/signal"
945         "reflect"
946         "runtime"
947         "runtime/cgo"
948         "sync"
949         "syscall"
950         "testing"
951         "time"
952         "unsafe"
953 )
954
955 // alignment
956
957 func testAlign(t *testing.T) {
958         var evt C.SDL_KeyboardEvent
959         C.makeEvent(&evt)
960         if C.same(&evt, evt.typ, evt.which, evt.state, evt.keysym.scancode, evt.keysym.sym, evt.keysym.mod, evt.keysym.unicode) == 0 {
961                 t.Error("*** bad alignment")
962                 C.cTest(&evt)
963                 t.Errorf("Go: %#x %#x %#x %#x %#x %#x %#x\n",
964                         evt.typ, evt.which, evt.state, evt.keysym.scancode,
965                         evt.keysym.sym, evt.keysym.mod, evt.keysym.unicode)
966                 t.Error(evt)
967         }
968 }
969
970 // api
971
972 const greeting = "hello, world"
973
974 type testPair struct {
975         Name      string
976         Got, Want interface{}
977 }
978
979 var testPairs = []testPair{
980         {"GoString", C.GoString(C.greeting), greeting},
981         {"GoStringN", C.GoStringN(C.greeting, 5), greeting[:5]},
982         {"GoBytes", C.GoBytes(unsafe.Pointer(C.greeting), 5), []byte(greeting[:5])},
983 }
984
985 func testHelpers(t *testing.T) {
986         for _, pair := range testPairs {
987                 if !reflect.DeepEqual(pair.Got, pair.Want) {
988                         t.Errorf("%s: got %#v, want %#v", pair.Name, pair.Got, pair.Want)
989                 }
990         }
991 }
992
993 // basic test cases
994
995 const EINVAL = C.EINVAL /* test #define */
996
997 var KILO = C.KILO
998
999 func uuidgen() {
1000         var uuid C.cgo_uuid_t
1001         C.uuid_generate(&uuid[0])
1002 }
1003
1004 func Strtol(s string, base int) (int, error) {
1005         p := C.CString(s)
1006         n, err := C.strtol(p, nil, C.int(base))
1007         C.free(unsafe.Pointer(p))
1008         return int(n), err
1009 }
1010
1011 func Atol(s string) int {
1012         p := C.CString(s)
1013         n := C.atol(p)
1014         C.free(unsafe.Pointer(p))
1015         return int(n)
1016 }
1017
1018 func testConst(t *testing.T) {
1019         C.myConstFunc(nil, 0, nil)
1020 }
1021
1022 func testEnum(t *testing.T) {
1023         if C.Enum1 != 1 || C.Enum2 != 2 {
1024                 t.Error("bad enum", C.Enum1, C.Enum2)
1025         }
1026 }
1027
1028 func testNamedEnum(t *testing.T) {
1029         e := new(C.enum_E)
1030
1031         *e = C.Enum1
1032         if *e != 1 {
1033                 t.Error("bad enum", C.Enum1)
1034         }
1035
1036         *e = C.Enum2
1037         if *e != 2 {
1038                 t.Error("bad enum", C.Enum2)
1039         }
1040 }
1041
1042 func testCastToEnum(t *testing.T) {
1043         e := C.enum_E(C.Enum1)
1044         if e != 1 {
1045                 t.Error("bad enum", C.Enum1)
1046         }
1047
1048         e = C.enum_E(C.Enum2)
1049         if e != 2 {
1050                 t.Error("bad enum", C.Enum2)
1051         }
1052 }
1053
1054 func testAtol(t *testing.T) {
1055         l := Atol("123")
1056         if l != 123 {
1057                 t.Error("Atol 123: ", l)
1058         }
1059 }
1060
1061 func testErrno(t *testing.T) {
1062         p := C.CString("no-such-file")
1063         m := C.CString("r")
1064         f, err := C.fopen(p, m)
1065         C.free(unsafe.Pointer(p))
1066         C.free(unsafe.Pointer(m))
1067         if err == nil {
1068                 C.fclose(f)
1069                 t.Fatalf("C.fopen: should fail")
1070         }
1071         if err != syscall.ENOENT {
1072                 t.Fatalf("C.fopen: unexpected error: %v", err)
1073         }
1074 }
1075
1076 func testMultipleAssign(t *testing.T) {
1077         p := C.CString("234")
1078         n, m := C.strtol(p, nil, 345), C.strtol(p, nil, 10)
1079         if runtime.GOOS == "openbsd" {
1080                 // Bug in OpenBSD strtol(3) - base > 36 succeeds.
1081                 if (n != 0 && n != 239089) || m != 234 {
1082                         t.Fatal("Strtol x2: ", n, m)
1083                 }
1084         } else if n != 0 || m != 234 {
1085                 t.Fatal("Strtol x2: ", n, m)
1086         }
1087         C.free(unsafe.Pointer(p))
1088 }
1089
1090 var (
1091         cuint  = (C.uint)(0)
1092         culong C.ulong
1093         cchar  C.char
1094 )
1095
1096 type Context struct {
1097         ctx *C.struct_ibv_context
1098 }
1099
1100 func benchCgoCall(b *testing.B) {
1101         b.Run("add-int", func(b *testing.B) {
1102                 const x = C.int(2)
1103                 const y = C.int(3)
1104
1105                 for i := 0; i < b.N; i++ {
1106                         C.add(x, y)
1107                 }
1108         })
1109
1110         b.Run("one-pointer", func(b *testing.B) {
1111                 var a0 C.VkDeviceCreateInfo
1112                 for i := 0; i < b.N; i++ {
1113                         C.handleComplexPointer(&a0)
1114                 }
1115         })
1116         b.Run("string-pointer-escape", func(b *testing.B) {
1117                 for i := 0; i < b.N; i++ {
1118                         var s string
1119                         C.handleGoStringPointerEscape(unsafe.Pointer(&s))
1120                 }
1121         })
1122         b.Run("string-pointer-noescape", func(b *testing.B) {
1123                 for i := 0; i < b.N; i++ {
1124                         var s string
1125                         C.handleGoStringPointerNoescape(unsafe.Pointer(&s))
1126                 }
1127         })
1128         b.Run("eight-pointers", func(b *testing.B) {
1129                 var a0, a1, a2, a3, a4, a5, a6, a7 C.VkDeviceCreateInfo
1130                 for i := 0; i < b.N; i++ {
1131                         C.handleComplexPointer8(&a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7)
1132                 }
1133         })
1134         b.Run("eight-pointers-nil", func(b *testing.B) {
1135                 var a0, a1, a2, a3, a4, a5, a6, a7 *C.VkDeviceCreateInfo
1136                 for i := 0; i < b.N; i++ {
1137                         C.handleComplexPointer8(a0, a1, a2, a3, a4, a5, a6, a7)
1138                 }
1139         })
1140         b.Run("eight-pointers-array", func(b *testing.B) {
1141                 var a [8]C.VkDeviceCreateInfo
1142                 for i := 0; i < b.N; i++ {
1143                         C.handleComplexPointer8(&a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7])
1144                 }
1145         })
1146         b.Run("eight-pointers-slice", func(b *testing.B) {
1147                 a := make([]C.VkDeviceCreateInfo, 8)
1148                 for i := 0; i < b.N; i++ {
1149                         C.handleComplexPointer8(&a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7])
1150                 }
1151         })
1152 }
1153
1154 // Benchmark measuring overhead from Go to C and back to Go (via a callback)
1155 func benchCallback(b *testing.B) {
1156         var x = false
1157         for i := 0; i < b.N; i++ {
1158                 nestedCall(func() { x = true })
1159         }
1160         if !x {
1161                 b.Fatal("nestedCall was not invoked")
1162         }
1163 }
1164
1165 var sinkString string
1166
1167 func benchGoString(b *testing.B) {
1168         for i := 0; i < b.N; i++ {
1169                 sinkString = C.GoString(C.cstr)
1170         }
1171         const want = "abcefghijklmnopqrstuvwxyzABCEFGHIJKLMNOPQRSTUVWXYZ1234567890"
1172         if sinkString != want {
1173                 b.Fatalf("%q != %q", sinkString, want)
1174         }
1175 }
1176
1177 // Static (build-time) test that syntax traversal visits all operands of s[i:j:k].
1178 func sliceOperands(array [2000]int) {
1179         _ = array[C.KILO:C.KILO:C.KILO] // no type error
1180 }
1181
1182 // set in cgo_thread_lock.go init
1183 var testThreadLockFunc = func(*testing.T) {}
1184
1185 // complex alignment
1186
1187 func TestComplexAlign(t *testing.T) {
1188         if C.cplxAlign.x != 3.14 {
1189                 t.Errorf("got %v, expected 3.14", C.cplxAlign.x)
1190         }
1191         if C.cplxAlign.y != 2.17 {
1192                 t.Errorf("got %v, expected 2.17", C.cplxAlign.y)
1193         }
1194 }
1195
1196 // constants and pointer checking
1197
1198 func testCheckConst(t *testing.T) {
1199         // The test is that this compiles successfully.
1200         p := C.malloc(C.size_t(unsafe.Sizeof(C.int(0))))
1201         defer C.free(p)
1202         C.CheckConstFunc(&C.CheckConstStruct{(*C.int)(p)}, C.CheckConstVal)
1203 }
1204
1205 // duplicate symbol
1206
1207 func duplicateSymbols() {
1208         fmt.Printf("%v %v %v\n", C.base_symbol, C.alias_one, C.alias_two)
1209 }
1210
1211 // environment
1212
1213 // This is really an os package test but here for convenience.
1214 func testSetEnv(t *testing.T) {
1215         if runtime.GOOS == "windows" {
1216                 // Go uses SetEnvironmentVariable on windows. However,
1217                 // C runtime takes a *copy* at process startup of the
1218                 // OS environment, and stores it in environ/envp.
1219                 // It is this copy that getenv/putenv manipulate.
1220                 t.Logf("skipping test")
1221                 return
1222         }
1223         const key = "CGO_OS_TEST_KEY"
1224         const val = "CGO_OS_TEST_VALUE"
1225         os.Setenv(key, val)
1226         keyc := C.CString(key)
1227         defer C.free(unsafe.Pointer(keyc))
1228         v := C.getenv(keyc)
1229         if uintptr(unsafe.Pointer(v)) == 0 {
1230                 t.Fatal("getenv returned NULL")
1231         }
1232         vs := C.GoString(v)
1233         if vs != val {
1234                 t.Fatalf("getenv() = %q; want %q", vs, val)
1235         }
1236 }
1237
1238 // function pointer variables
1239
1240 func callBridge(f C.intFunc) int {
1241         return int(C.bridge_int_func(f))
1242 }
1243
1244 func callCBridge(f C.intFunc) C.int {
1245         return C.bridge_int_func(f)
1246 }
1247
1248 func testFpVar(t *testing.T) {
1249         const expected = 42
1250         f := C.intFunc(C.fortytwo)
1251         res1 := C.bridge_int_func(f)
1252         if r1 := int(res1); r1 != expected {
1253                 t.Errorf("got %d, want %d", r1, expected)
1254         }
1255         res2 := callCBridge(f)
1256         if r2 := int(res2); r2 != expected {
1257                 t.Errorf("got %d, want %d", r2, expected)
1258         }
1259         r3 := callBridge(f)
1260         if r3 != expected {
1261                 t.Errorf("got %d, want %d", r3, expected)
1262         }
1263 }
1264
1265 // issue 1222
1266 type AsyncEvent struct {
1267         event C.struct_ibv_async_event
1268 }
1269
1270 // issue 1635
1271
1272 func test1635(t *testing.T) {
1273         C.scatter()
1274         if v := C.hola; v != 0 {
1275                 t.Fatalf("C.hola is %d, should be 0", v)
1276         }
1277         if v := C.testHola(); v != 0 {
1278                 t.Fatalf("C.testHola() is %d, should be 0", v)
1279         }
1280 }
1281
1282 // issue 2470
1283
1284 func testUnsignedInt(t *testing.T) {
1285         a := (int64)(C.UINT32VAL)
1286         b := (int64)(0xc008427b)
1287         if a != b {
1288                 t.Errorf("Incorrect unsigned int - got %x, want %x", a, b)
1289         }
1290 }
1291
1292 // issue 3250
1293
1294 func test3250(t *testing.T) {
1295         if runtime.GOOS == "windows" {
1296                 t.Skip("not applicable on windows")
1297         }
1298
1299         t.Skip("skipped, see golang.org/issue/5885")
1300         var (
1301                 thres = 1
1302                 sig   = syscall_dot_SIGCHLD
1303         )
1304         type result struct {
1305                 n   int
1306                 sig os.Signal
1307         }
1308         var (
1309                 sigCh     = make(chan os.Signal, 10)
1310                 waitStart = make(chan struct{})
1311                 waitDone  = make(chan result)
1312         )
1313
1314         signal.Notify(sigCh, sig)
1315
1316         go func() {
1317                 n := 0
1318                 alarm := time.After(time.Second * 3)
1319                 for {
1320                         select {
1321                         case <-waitStart:
1322                                 waitStart = nil
1323                         case v := <-sigCh:
1324                                 n++
1325                                 if v != sig || n > thres {
1326                                         waitDone <- result{n, v}
1327                                         return
1328                                 }
1329                         case <-alarm:
1330                                 waitDone <- result{n, sig}
1331                                 return
1332                         }
1333                 }
1334         }()
1335
1336         waitStart <- struct{}{}
1337         C.testSendSIG()
1338         r := <-waitDone
1339         if r.sig != sig {
1340                 t.Fatalf("received signal %v, but want %v", r.sig, sig)
1341         }
1342         t.Logf("got %d signals\n", r.n)
1343         if r.n <= thres {
1344                 t.Fatalf("expected more than %d", thres)
1345         }
1346 }
1347
1348 // issue 3261
1349
1350 func testLibgcc(t *testing.T) {
1351         var table = []struct {
1352                 in, out C.int
1353         }{
1354                 {0, 0},
1355                 {1, 1},
1356                 {-42, 42},
1357                 {1000300, 1000300},
1358                 {1 - 1<<31, 1<<31 - 1},
1359         }
1360         for _, v := range table {
1361                 if o := C.vabs(v.in); o != v.out {
1362                         t.Fatalf("abs(%d) got %d, should be %d", v.in, o, v.out)
1363                         return
1364                 }
1365         }
1366 }
1367
1368 // issue 3729
1369
1370 func test3729(t *testing.T) {
1371         if runtime.GOOS == "windows" {
1372                 t.Skip("skipping on windows")
1373         }
1374
1375         _, e := C.g()
1376         if e != syscall.E2BIG {
1377                 t.Errorf("got %q, expect %q", e, syscall.E2BIG)
1378         }
1379         _, e = C.g2(C.EINVAL, C._expA, C._expB, C._expC, C._expD)
1380         if e != syscall.EINVAL {
1381                 t.Errorf("got %q, expect %q", e, syscall.EINVAL)
1382         }
1383 }
1384
1385 // issue 3945
1386
1387 func testPrintf(t *testing.T) {
1388         C.say()
1389 }
1390
1391 // issue 4054
1392
1393 var issue4054a = []int{C.A, C.B, C.C, C.D, C.E, C.F, C.G, C.H, C.I, C.J}
1394
1395 // issue 4339
1396
1397 func test4339(t *testing.T) {
1398         C.handle4339(&C.exported4339)
1399 }
1400
1401 // issue 4417
1402
1403 func testBoolAlign(t *testing.T) {
1404         b := C.c_bool(true, true, 10, true, false)
1405         if b != 10 {
1406                 t.Fatalf("found %d expected 10\n", b)
1407         }
1408         b = C.c_bool(true, true, 5, true, true)
1409         if b != 5 {
1410                 t.Fatalf("found %d expected 5\n", b)
1411         }
1412         b = C.c_bool(true, true, 3, true, false)
1413         if b != 3 {
1414                 t.Fatalf("found %d expected 3\n", b)
1415         }
1416         b = C.c_bool(false, false, 1, true, false)
1417         if b != 1 {
1418                 t.Fatalf("found %d expected 1\n", b)
1419         }
1420         b = C.c_bool(false, true, 200, true, false)
1421         if b != 200 {
1422                 t.Fatalf("found %d expected 200\n", b)
1423         }
1424 }
1425
1426 // issue 4857
1427
1428 func test4857() {
1429         _ = C.issue4857()
1430 }
1431
1432 // issue 5224
1433
1434 func testCflags(t *testing.T) {
1435         is_windows := C.is_windows == 1
1436         if is_windows != (runtime.GOOS == "windows") {
1437                 t.Errorf("is_windows: %v, runtime.GOOS: %s", is_windows, runtime.GOOS)
1438         }
1439         if C.common != 123 {
1440                 t.Errorf("common: %v (expected 123)", C.common)
1441         }
1442 }
1443
1444 // issue 5227
1445
1446 func test5227(t *testing.T) {
1447         C.init()
1448 }
1449
1450 func selectfont() C.Fontinfo {
1451         return C.SansTypeface
1452 }
1453
1454 // issue 5242
1455
1456 func test5242(t *testing.T) {
1457         if got := C.issue5242(C.foo{}, C.bar{}); got != 5242 {
1458                 t.Errorf("got %v", got)
1459         }
1460 }
1461
1462 func test5603(t *testing.T) {
1463         var x [5]int64
1464         exp := int64(C.issue5603exp)
1465         x[0] = int64(C.issue5603foo0())
1466         x[1] = int64(C.issue5603foo1(nil))
1467         x[2] = int64(C.issue5603foo2(nil, nil))
1468         x[3] = int64(C.issue5603foo3(nil, nil, nil))
1469         x[4] = int64(C.issue5603foo4(nil, nil, nil, nil))
1470         for i, v := range x {
1471                 if v != exp {
1472                         t.Errorf("issue5603foo%d() returns %v, expected %v", i, v, exp)
1473                 }
1474         }
1475 }
1476
1477 // issue 5337
1478
1479 func test5337(t *testing.T) {
1480         C.test5337()
1481 }
1482
1483 // issue 5740
1484
1485 func test5740(t *testing.T) {
1486         if v := C.test5740a() + C.test5740b(); v != 5 {
1487                 t.Errorf("expected 5, got %v", v)
1488         }
1489 }
1490
1491 // issue 5986
1492
1493 func test5986(t *testing.T) {
1494         C.output5986()
1495 }
1496
1497 // issue 6128
1498
1499 func test6128() {
1500         // nothing to run, just make sure this compiles.
1501         _ = C.X
1502 }
1503
1504 // issue 6390
1505
1506 func test6390(t *testing.T) {
1507         p1 := C.malloc(1024)
1508         if p1 == nil {
1509                 t.Fatalf("C.malloc(1024) returned nil")
1510         }
1511         p2 := C.malloc(0)
1512         if p2 == nil {
1513                 t.Fatalf("C.malloc(0) returned nil")
1514         }
1515         C.free(p1)
1516         C.free(p2)
1517 }
1518
1519 func test6472() {
1520         // nothing to run, just make sure this compiles
1521         s := new(C.z)
1522         println(s.y[0].x)
1523 }
1524
1525 // issue 6506
1526
1527 func test6506() {
1528         // nothing to run, just make sure this compiles
1529         var x C.size_t
1530
1531         C.calloc(x, x)
1532         C.malloc(x)
1533         C.realloc(nil, x)
1534         C.memcpy(nil, nil, x)
1535         C.memcmp(nil, nil, x)
1536         C.memmove(nil, nil, x)
1537         C.strncpy(nil, nil, x)
1538         C.strncmp(nil, nil, x)
1539         C.strncat(nil, nil, x)
1540         x = C.strxfrm(nil, nil, x)
1541         C.memchr(nil, 0, x)
1542         x = C.strcspn(nil, nil)
1543         x = C.strspn(nil, nil)
1544         C.memset(nil, 0, x)
1545         x = C.strlen(nil)
1546         _ = x
1547 }
1548
1549 // issue 6612
1550
1551 func testNaming(t *testing.T) {
1552         C.myfunc()
1553         C.myfunc_def()
1554         if v := C.myvar; v != 5 {
1555                 t.Errorf("C.myvar = %d, want 5", v)
1556         }
1557         if v := C.myvar_def; v != 5 {
1558                 t.Errorf("C.myvar_def = %d, want 5", v)
1559         }
1560         if s := C.GoString(C.mytext); s != "abcdef" {
1561                 t.Errorf("C.mytext = %q, want %q", s, "abcdef")
1562         }
1563         if s := C.GoString(C.mytext_def); s != "abcdef" {
1564                 t.Errorf("C.mytext_def = %q, want %q", s, "abcdef")
1565         }
1566         if c := C.myenum; c != 1234 {
1567                 t.Errorf("C.myenum = %v, want 1234", c)
1568         }
1569         if c := C.myenum_def; c != 1234 {
1570                 t.Errorf("C.myenum_def = %v, want 1234", c)
1571         }
1572         {
1573                 const c = C.myenum
1574                 if c != 1234 {
1575                         t.Errorf("C.myenum as const = %v, want 1234", c)
1576                 }
1577         }
1578         {
1579                 const c = C.myenum_def
1580                 if c != 1234 {
1581                         t.Errorf("C.myenum as const = %v, want 1234", c)
1582                 }
1583         }
1584         if c := C.myint_def; c != 12345 {
1585                 t.Errorf("C.myint_def = %v, want 12345", c)
1586         }
1587         {
1588                 const c = C.myint_def
1589                 if c != 12345 {
1590                         t.Errorf("C.myint as const = %v, want 12345", c)
1591                 }
1592         }
1593
1594         if c := C.myfloat_def; c != 1.5 {
1595                 t.Errorf("C.myint_def = %v, want 1.5", c)
1596         }
1597         {
1598                 const c = C.myfloat_def
1599                 if c != 1.5 {
1600                         t.Errorf("C.myint as const = %v, want 1.5", c)
1601                 }
1602         }
1603
1604         if s := C.mystring_def; s != "hello" {
1605                 t.Errorf("C.mystring_def = %q, want %q", s, "hello")
1606         }
1607 }
1608
1609 // issue 6907
1610
1611 func test6907(t *testing.T) {
1612         want := "yarn"
1613         if got := C.GoString(C.Issue6907CopyString(want)); got != want {
1614                 t.Errorf("C.GoString(C.Issue6907CopyString(%q)) == %q, want %q", want, got, want)
1615         }
1616 }
1617
1618 // issue 7560
1619
1620 func test7560(t *testing.T) {
1621         // some mingw don't implement __packed__ correctly.
1622         if C.offset7560() != 1 {
1623                 t.Skip("C compiler did not pack struct")
1624         }
1625
1626         // C.misaligned should have x but then a padding field to get to the end of the struct.
1627         // There should not be a field named 'y'.
1628         var v C.misaligned
1629         rt := reflect.TypeOf(&v).Elem()
1630         if rt.NumField() != 2 || rt.Field(0).Name != "x" || rt.Field(1).Name != "_" {
1631                 t.Errorf("unexpected fields in C.misaligned:\n")
1632                 for i := 0; i < rt.NumField(); i++ {
1633                         t.Logf("%+v\n", rt.Field(i))
1634                 }
1635         }
1636 }
1637
1638 // issue 7786
1639
1640 func f() {
1641         var x1 *C.typedef_test7786
1642         var x2 *C.struct_test7786
1643         x1 = x2
1644         x2 = x1
1645         C.f7786(x1)
1646         C.f7786(x2)
1647         C.g7786(x1)
1648         C.g7786(x2)
1649
1650         var b1 *C.typedef_body7786
1651         var b2 *C.struct_body7786
1652         b1 = b2
1653         b2 = b1
1654         C.b7786(b1)
1655         C.b7786(b2)
1656         C.c7786(b1)
1657         C.c7786(b2)
1658
1659         var u1 *C.typedef_union7786
1660         var u2 *C.union_union7786
1661         u1 = u2
1662         u2 = u1
1663         C.u7786(u1)
1664         C.u7786(u2)
1665         C.v7786(u1)
1666         C.v7786(u2)
1667 }
1668
1669 // issue 8092
1670
1671 func test8092(t *testing.T) {
1672         tests := []struct {
1673                 s    string
1674                 a, b *C.char
1675         }{
1676                 {"text", &C.text[0], C.ctext()},
1677                 {"data", &C.data[0], C.cdata()},
1678         }
1679         for _, test := range tests {
1680                 if test.a != test.b {
1681                         t.Errorf("%s: pointer mismatch: %v != %v", test.s, test.a, test.b)
1682                 }
1683                 if got := C.GoString(test.a); got != test.s {
1684                         t.Errorf("%s: points at %#v, want %#v", test.s, got, test.s)
1685                 }
1686         }
1687 }
1688
1689 // issues 8368 and 8441
1690
1691 func issue8368(one *C.struct_one, two *C.struct_two) {
1692 }
1693
1694 func issue8441(one *C.one, two *C.two) {
1695         issue8441(two.x, one.x)
1696 }
1697
1698 // issue 8428
1699
1700 var _ = C.struct_issue8428one{
1701         b: C.char(0),
1702         // The trailing rest field is not available in cgo.
1703         // See issue 11925.
1704         // rest: [0]C.char{},
1705 }
1706
1707 var _ = C.struct_issue8428two{
1708         p:    unsafe.Pointer(nil),
1709         b:    C.char(0),
1710         rest: [0]C.char{},
1711 }
1712
1713 var _ = C.struct_issue8428three{
1714         w: [1][2][3][0]C.char{},
1715         x: [2][3][0][1]C.char{},
1716         y: [3][0][1][2]C.char{},
1717         z: [0][1][2][3]C.char{},
1718 }
1719
1720 // issue 8811
1721
1722 func test8811(t *testing.T) {
1723         C.issue8811Execute()
1724 }
1725
1726 // issue 9557
1727
1728 func test9557(t *testing.T) {
1729         // implicitly dereference a Go variable
1730         foo := C.issue9557foo
1731         if v := foo.a; v != 42 {
1732                 t.Fatalf("foo.a expected 42, but got %d", v)
1733         }
1734
1735         // explicitly dereference a C variable
1736         if v := (*C.issue9557foo).a; v != 42 {
1737                 t.Fatalf("(*C.issue9557foo).a expected 42, but is %d", v)
1738         }
1739
1740         // implicitly dereference a C variable
1741         if v := C.issue9557foo.a; v != 42 {
1742                 t.Fatalf("C.issue9557foo.a expected 42, but is %d", v)
1743         }
1744 }
1745
1746 // issue 8331 part 1
1747
1748 func issue8331a() C.issue8331 {
1749         return issue8331Var
1750 }
1751
1752 // issue 10303
1753
1754 func test10303(t *testing.T, n int) {
1755         if runtime.Compiler == "gccgo" {
1756                 t.Skip("gccgo permits C pointers on the stack")
1757         }
1758
1759         // Run at a few different stack depths just to avoid an unlucky pass
1760         // due to variables ending up on different pages.
1761         if n > 0 {
1762                 test10303(t, n-1)
1763         }
1764         if t.Failed() {
1765                 return
1766         }
1767         var x, y, z, v, si C.int
1768         var s C.Struct
1769         C.setintstar(&x)
1770         C.setintptr(&y)
1771         C.setvoidptr(unsafe.Pointer(&v))
1772         s.P = &si
1773         C.setstruct(s)
1774
1775         if uintptr(unsafe.Pointer(&x))&^0xfff == uintptr(unsafe.Pointer(&z))&^0xfff {
1776                 t.Error("C int* argument on stack")
1777         }
1778         if uintptr(unsafe.Pointer(&y))&^0xfff == uintptr(unsafe.Pointer(&z))&^0xfff {
1779                 t.Error("C intptr argument on stack")
1780         }
1781         if uintptr(unsafe.Pointer(&v))&^0xfff == uintptr(unsafe.Pointer(&z))&^0xfff {
1782                 t.Error("C void* argument on stack")
1783         }
1784         if uintptr(unsafe.Pointer(&si))&^0xfff == uintptr(unsafe.Pointer(&z))&^0xfff {
1785                 t.Error("C struct field pointer on stack")
1786         }
1787 }
1788
1789 // issue 11925
1790
1791 func test11925(t *testing.T) {
1792         if C.sizeof_struct_a11925 != unsafe.Sizeof(C.struct_a11925{}) {
1793                 t.Errorf("size of a changed: C %d, Go %d", C.sizeof_struct_a11925, unsafe.Sizeof(C.struct_a11925{}))
1794         }
1795         if C.sizeof_struct_b11925 != unsafe.Sizeof(C.struct_b11925{}) {
1796                 t.Errorf("size of b changed: C %d, Go %d", C.sizeof_struct_b11925, unsafe.Sizeof(C.struct_b11925{}))
1797         }
1798 }
1799
1800 // issue 12030
1801
1802 func test12030(t *testing.T) {
1803         buf := (*C.char)(C.malloc(256))
1804         defer C.free(unsafe.Pointer(buf))
1805         for _, f := range []float64{1.0, 2.0, 3.14} {
1806                 C.issue12030conv(buf, C.double(f))
1807                 got := C.GoString(buf)
1808                 if want := fmt.Sprintf("d=%g", f); got != want {
1809                         t.Fatalf("C.sprintf failed for %g: %q != %q", f, got, want)
1810                 }
1811         }
1812 }
1813
1814 // issue 13402
1815
1816 var _ C.complexfloat
1817 var _ C.complexdouble
1818
1819 // issue 13930
1820 // Test that cgo's multiple-value special form for
1821 // C function calls works in variable declaration statements.
1822
1823 var _, _ = C.abs(0)
1824
1825 // issue 14838
1826
1827 func test14838(t *testing.T) {
1828         data := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
1829         cData := C.CBytes(data)
1830         defer C.free(cData)
1831
1832         if C.check_cbytes((*C.char)(cData), C.size_t(len(data))) == 0 {
1833                 t.Fatalf("mismatched data: expected %v, got %v", data, (*(*[10]byte)(unsafe.Pointer(cData)))[:])
1834         }
1835 }
1836
1837 // issue 17065
1838
1839 var sink C.int
1840
1841 func test17065(t *testing.T) {
1842         if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
1843                 t.Skip("broken on darwin; issue 17065")
1844         }
1845         for i := range C.ii {
1846                 sink = C.ii[i]
1847         }
1848 }
1849
1850 // issue 17537
1851
1852 func test17537(t *testing.T) {
1853         v := C.S17537{i: 17537}
1854         if got, want := C.I17537(&v), C.int(17537); got != want {
1855                 t.Errorf("got %d, want %d", got, want)
1856         }
1857
1858         p := (*C.char)(C.malloc(1))
1859         *p = 17
1860         if got, want := C.F17537(&p), C.int(17); got != want {
1861                 t.Errorf("got %d, want %d", got, want)
1862         }
1863
1864         C.F18298(nil)
1865         var v18298 C.T18298_2
1866         C.G18298(C.T18298_1(v18298))
1867 }
1868
1869 // issue 17723
1870
1871 func testAPI() {
1872         var cs *C.char
1873         cs = C.CString("hello")
1874         defer C.free(unsafe.Pointer(cs))
1875         var s string
1876         s = C.GoString((*C.char)(C.api_hello))
1877         s = C.GoStringN((*C.char)(C.api_hello), C.int(6))
1878         var b []byte
1879         b = C.GoBytes(unsafe.Pointer(C.api_hello), C.int(6))
1880         _, _ = s, b
1881         C.cstring_pointer_fun(nil)
1882 }
1883
1884 // issue 18126
1885
1886 func test18126(t *testing.T) {
1887         p := C.malloc(1)
1888         _, err := C.Issue18126C(&p)
1889         C.free(p)
1890         _ = err
1891 }
1892
1893 // issue 18720
1894
1895 func test18720(t *testing.T) {
1896         if got, want := C.HELLO_WORLD, "hello\000world"; got != want {
1897                 t.Errorf("C.HELLO_WORLD == %q, expected %q", got, want)
1898         }
1899
1900         if got, want := C.VAR1, C.int(5); got != want {
1901                 t.Errorf("C.VAR1 == %v, expected %v", got, want)
1902         }
1903
1904         if got, want := *C.ADDR, C.int(5); got != want {
1905                 t.Errorf("*C.ADDR == %v, expected %v", got, want)
1906         }
1907
1908         if got, want := C.CALL, C.int(6); got != want {
1909                 t.Errorf("C.CALL == %v, expected %v", got, want)
1910         }
1911
1912         if got, want := C.CALL, C.int(7); got != want {
1913                 t.Errorf("C.CALL == %v, expected %v", got, want)
1914         }
1915
1916         // Issue 20125.
1917         if got, want := C.SIZE_OF_FOO, 1; got != want {
1918                 t.Errorf("C.SIZE_OF_FOO == %v, expected %v", got, want)
1919         }
1920 }
1921
1922 // issue 20129
1923
1924 func test20129(t *testing.T) {
1925         if C.issue20129 != 0 {
1926                 t.Fatal("test is broken")
1927         }
1928         C.issue20129Foo()
1929         if C.issue20129 != 1 {
1930                 t.Errorf("got %v but expected %v", C.issue20129, 1)
1931         }
1932         C.issue20129Bar()
1933         if C.issue20129 != 2 {
1934                 t.Errorf("got %v but expected %v", C.issue20129, 2)
1935         }
1936 }
1937
1938 // issue 20369
1939
1940 func test20369(t *testing.T) {
1941         if C.XUINT64_MAX != math.MaxUint64 {
1942                 t.Fatalf("got %v, want %v", uint64(C.XUINT64_MAX), uint64(math.MaxUint64))
1943         }
1944 }
1945
1946 // issue 21668
1947
1948 var issue21668_X = C.x21668
1949
1950 // issue 21708
1951
1952 func test21708(t *testing.T) {
1953         if got, want := C.CAST_TO_INT64, -1; got != want {
1954                 t.Errorf("C.CAST_TO_INT64 == %v, expected %v", got, want)
1955         }
1956 }
1957
1958 // issue 21809
1959
1960 func test21809(t *testing.T) {
1961         longVar := C.long(3)
1962         typedefVar := C.MySigned_t(4)
1963         typedefTypedefVar := C.MySigned2_t(5)
1964
1965         // all three should be considered identical to `long`
1966         if ret := C.takes_long(longVar); ret != 9 {
1967                 t.Errorf("got %v but expected %v", ret, 9)
1968         }
1969         if ret := C.takes_long(typedefVar); ret != 16 {
1970                 t.Errorf("got %v but expected %v", ret, 16)
1971         }
1972         if ret := C.takes_long(typedefTypedefVar); ret != 25 {
1973                 t.Errorf("got %v but expected %v", ret, 25)
1974         }
1975
1976         // They should also be identical to the typedef'd type
1977         if ret := C.takes_typedef(longVar); ret != 9 {
1978                 t.Errorf("got %v but expected %v", ret, 9)
1979         }
1980         if ret := C.takes_typedef(typedefVar); ret != 16 {
1981                 t.Errorf("got %v but expected %v", ret, 16)
1982         }
1983         if ret := C.takes_typedef(typedefTypedefVar); ret != 25 {
1984                 t.Errorf("got %v but expected %v", ret, 25)
1985         }
1986 }
1987
1988 // issue 22906
1989
1990 func test22906(t *testing.T) {
1991         var x1 C.jobject = 0 // Note: 0, not nil. That makes sure we use uintptr for these types.
1992         _ = x1
1993         var x2 C.jclass = 0
1994         _ = x2
1995         var x3 C.jthrowable = 0
1996         _ = x3
1997         var x4 C.jstring = 0
1998         _ = x4
1999         var x5 C.jarray = 0
2000         _ = x5
2001         var x6 C.jbooleanArray = 0
2002         _ = x6
2003         var x7 C.jbyteArray = 0
2004         _ = x7
2005         var x8 C.jcharArray = 0
2006         _ = x8
2007         var x9 C.jshortArray = 0
2008         _ = x9
2009         var x10 C.jintArray = 0
2010         _ = x10
2011         var x11 C.jlongArray = 0
2012         _ = x11
2013         var x12 C.jfloatArray = 0
2014         _ = x12
2015         var x13 C.jdoubleArray = 0
2016         _ = x13
2017         var x14 C.jobjectArray = 0
2018         _ = x14
2019         var x15 C.jweak = 0
2020         _ = x15
2021 }
2022
2023 // issue 22958
2024 // Nothing to run, just make sure this compiles.
2025 var Vissue22958 C.issue22958Type
2026
2027 func test23356(t *testing.T) {
2028         if got, want := C.a(), C.int(5); got != want {
2029                 t.Errorf("C.a() == %v, expected %v", got, want)
2030         }
2031         if got, want := C.r(), C.int(3); got != want {
2032                 t.Errorf("C.r() == %v, expected %v", got, want)
2033         }
2034 }
2035
2036 // issue 23720
2037
2038 func Issue23720F() {
2039         var x C.issue23720A
2040         C.issue23720F(x)
2041 }
2042
2043 // issue 24206
2044
2045 func test24206(t *testing.T) {
2046         if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
2047                 t.Skipf("skipping on %s/%s", runtime.GOOS, runtime.GOARCH)
2048         }
2049
2050         if l := len(C.GoString(C.dangerousString1())); l != 123 {
2051                 t.Errorf("Incorrect string length - got %d, want 123", l)
2052         }
2053         if l := len(C.GoString(C.dangerousString2())); l != 4096+123 {
2054                 t.Errorf("Incorrect string length - got %d, want %d", l, 4096+123)
2055         }
2056 }
2057
2058 // issue 25143
2059
2060 func issue25143sum(ns ...C.int) C.int {
2061         total := C.int(0)
2062         for _, n := range ns {
2063                 total += n
2064         }
2065         return total
2066 }
2067
2068 func test25143(t *testing.T) {
2069         if got, want := issue25143sum(1, 2, 3), C.int(6); got != want {
2070                 t.Errorf("issue25143sum(1, 2, 3) == %v, expected %v", got, want)
2071         }
2072 }
2073
2074 // issue 26066
2075 // Wrong type of constant with GCC 8 and newer.
2076
2077 func test26066(t *testing.T) {
2078         var i = int64(C.issue26066)
2079         if i != -1 {
2080                 t.Errorf("got %d, want -1", i)
2081         }
2082 }
2083
2084 // issue 26517
2085 var a C.TypeOne
2086 var b C.TypeTwo
2087
2088 // issue 27660
2089 // Stress the interaction between the race detector and cgo in an
2090 // attempt to reproduce the memory corruption described in #27660.
2091 // The bug was very timing sensitive; at the time of writing this
2092 // test would only trigger the bug about once out of every five runs.
2093
2094 func test27660(t *testing.T) {
2095         ctx, cancel := context.WithCancel(context.Background())
2096         defer cancel()
2097         ints := make([]int, 100)
2098         locks := make([]sync.Mutex, 100)
2099         // Slowly create threads so that ThreadSanitizer is forced to
2100         // frequently resize its SyncClocks.
2101         for i := 0; i < 100; i++ {
2102                 go func() {
2103                         for ctx.Err() == nil {
2104                                 // Sleep in C for long enough that it is likely that the runtime
2105                                 // will retake this goroutine's currently wired P.
2106                                 C.usleep(1000 /* 1ms */)
2107                                 runtime.Gosched() // avoid starvation (see #28701)
2108                         }
2109                 }()
2110                 go func() {
2111                         // Trigger lots of synchronization and memory reads/writes to
2112                         // increase the likelihood that the race described in #27660
2113                         // results in corruption of ThreadSanitizer's internal state
2114                         // and thus an assertion failure or segfault.
2115                         i := 0
2116                         for ctx.Err() == nil {
2117                                 j := rand.Intn(100)
2118                                 locks[j].Lock()
2119                                 ints[j]++
2120                                 locks[j].Unlock()
2121                                 // needed for gccgo, to avoid creation of an
2122                                 // unpreemptible "fast path" in this loop. Choice
2123                                 // of (1<<24) is somewhat arbitrary.
2124                                 if i%(1<<24) == 0 {
2125                                         runtime.Gosched()
2126                                 }
2127                                 i++
2128
2129                         }
2130                 }()
2131                 time.Sleep(time.Millisecond)
2132         }
2133 }
2134
2135 // issue 28540
2136
2137 func twoargsF() {
2138         var v struct{ p *byte }
2139         C.twoargs1(C.twoargs2(), C.twoargs3(unsafe.Pointer(&v)))
2140 }
2141
2142 // issue 28545
2143
2144 func issue28545G(p **C.char) {
2145         C.issue28545F(p, -1, (0))
2146         C.issue28545F(p, 2+3, complex(1, 1))
2147         C.issue28545F(p, issue28772Constant, issue28772Constant2)
2148 }
2149
2150 // issue 28772 part 1 - part 2 in testx.go
2151
2152 const issue28772Constant = C.issue28772Constant
2153
2154 // issue 28896
2155
2156 func offset(i int) uintptr {
2157         var pi C.innerPacked
2158         var po C.outerPacked
2159         var ui C.innerUnpacked
2160         var uo C.outerUnpacked
2161         switch i {
2162         case 0:
2163                 return unsafe.Offsetof(pi.f2)
2164         case 1:
2165                 return unsafe.Offsetof(po.g2)
2166         case 2:
2167                 return unsafe.Offsetof(ui.f2)
2168         case 3:
2169                 return unsafe.Offsetof(uo.g2)
2170         default:
2171                 panic("can't happen")
2172         }
2173 }
2174
2175 func test28896(t *testing.T) {
2176         for i := 0; i < 4; i++ {
2177                 c := uintptr(C.offset(C.int(i)))
2178                 g := offset(i)
2179                 if c != g {
2180                         t.Errorf("%d: C: %d != Go %d", i, c, g)
2181                 }
2182         }
2183 }
2184
2185 // issue 29383
2186 // cgo's /*line*/ comments failed when inserted after '/',
2187 // because the result looked like a "//" comment.
2188 // No runtime test; just make sure it compiles.
2189
2190 func Issue29383(n, size uint) int {
2191         if ^C.size_t(0)/C.size_t(n) < C.size_t(size) {
2192                 return 0
2193         }
2194         return 0
2195 }
2196
2197 // issue 29748
2198 // Error handling a struct initializer that requires pointer checking.
2199 // Compilation test only, nothing to run.
2200
2201 var Vissue29748 = C.f29748(&C.S29748{
2202         nil,
2203 })
2204
2205 func Fissue299748() {
2206         C.f29748(&C.S29748{
2207                 nil,
2208         })
2209 }
2210
2211 // issue 29781
2212
2213 var issue29781X struct{ X int }
2214
2215 func issue29781F(...int) int { return 0 }
2216
2217 func issue29781G() {
2218         var p *C.char
2219         C.issue29781F(&p, C.ISSUE29781C+1)
2220         C.issue29781F(nil, (C.int)(
2221                 0))
2222         C.issue29781F(&p, (C.int)(0))
2223         C.issue29781F(&p, (C.int)(
2224                 0))
2225         C.issue29781F(&p, (C.int)(issue29781X.
2226                 X))
2227 }
2228
2229 // issue 30065
2230
2231 func test30065(t *testing.T) {
2232         var a [256]byte
2233         b := []byte("a")
2234         C.memcpy(unsafe.Pointer(&a), unsafe.Pointer(&b[0]), 1)
2235         if a[0] != 'a' {
2236                 t.Errorf("&a failed: got %c, want %c", a[0], 'a')
2237         }
2238
2239         b = []byte("b")
2240         C.memcpy(unsafe.Pointer(&a[0]), unsafe.Pointer(&b[0]), 1)
2241         if a[0] != 'b' {
2242                 t.Errorf("&a[0] failed: got %c, want %c", a[0], 'b')
2243         }
2244
2245         d := make([]byte, 256)
2246         b = []byte("c")
2247         C.memcpy(unsafe.Pointer(&d[0]), unsafe.Pointer(&b[0]), 1)
2248         if d[0] != 'c' {
2249                 t.Errorf("&d[0] failed: got %c, want %c", d[0], 'c')
2250         }
2251 }
2252
2253 // issue 31093
2254 // No runtime test; just make sure it compiles.
2255
2256 func Issue31093() {
2257         C.issue31093F(C.ushort(0))
2258 }
2259
2260 // issue 32579
2261
2262 func test32579(t *testing.T) {
2263         var s [1]C.struct_S32579
2264         C.memset(unsafe.Pointer(&s[0].data[0]), 1, 1)
2265         if s[0].data[0] != 1 {
2266                 t.Errorf("&s[0].data[0] failed: got %d, want %d", s[0].data[0], 1)
2267         }
2268 }
2269
2270 // issue 37033, check if cgo.Handle works properly
2271
2272 func testHandle(t *testing.T) {
2273         ch := make(chan int)
2274
2275         for i := 0; i < 42; i++ {
2276                 h := cgo.NewHandle(ch)
2277                 go func() {
2278                         C.cFunc37033(C.uintptr_t(h))
2279                 }()
2280                 if v := <-ch; issue37033 != v {
2281                         t.Fatalf("unexpected receiving value: got %d, want %d", v, issue37033)
2282                 }
2283                 h.Delete()
2284         }
2285 }
2286
2287 // issue 38649
2288
2289 var issue38649 C.netbsd_gid = 42
2290
2291 // issue 39877
2292
2293 var issue39877 *C.void = nil
2294
2295 // issue 40494
2296 // No runtime test; just make sure it compiles.
2297
2298 func Issue40494() {
2299         C.issue40494(C.enum_Enum40494(C.X_40494), (*C.union_Union40494)(nil))
2300 }
2301
2302 // Issue 45451.
2303 func test45451(t *testing.T) {
2304         var u *C.issue45451
2305         typ := reflect.ValueOf(u).Type().Elem()
2306
2307         // The type is undefined in C so allocating it should panic.
2308         defer func() {
2309                 if r := recover(); r == nil {
2310                         t.Error("expected panic")
2311                 }
2312         }()
2313
2314         _ = reflect.New(typ)
2315         t.Errorf("reflect.New(%v) should have panicked", typ)
2316 }
2317
2318 // issue 52542
2319
2320 func func52542[T ~[]C.int]() {}
2321
2322 type type52542[T ~*C.float] struct{}