]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/runtime.h
[dev.garbage] all: merge default (f38460037b72) into dev.garbage
[gostls13.git] / src / runtime / runtime.h
1 // Copyright 2009 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 /*
6  * basic types
7  */
8 typedef signed char             int8;
9 typedef unsigned char           uint8;
10 typedef signed short            int16;
11 typedef unsigned short          uint16;
12 typedef signed int              int32;
13 typedef unsigned int            uint32;
14 typedef signed long long int    int64;
15 typedef unsigned long long int  uint64;
16 typedef float                   float32;
17 typedef double                  float64;
18
19 #ifdef _64BIT
20 typedef uint64          uintptr;
21 typedef int64           intptr;
22 typedef int64           intgo; // Go's int
23 typedef uint64          uintgo; // Go's uint
24 #else
25 typedef uint32          uintptr;
26 typedef int32           intptr;
27 typedef int32           intgo; // Go's int
28 typedef uint32          uintgo; // Go's uint
29 #endif
30
31 #ifdef _64BITREG
32 typedef uint64          uintreg;
33 #else
34 typedef uint32          uintreg;
35 #endif
36
37 /*
38  * get rid of C types
39  * the / / / forces a syntax error immediately,
40  * which will show "last name: XXunsigned".
41  */
42 #define unsigned                XXunsigned / / /
43 #define signed                  XXsigned / / /
44 #define char                    XXchar / / /
45 #define short                   XXshort / / /
46 #define int                     XXint / / /
47 #define long                    XXlong / / /
48 #define float                   XXfloat / / /
49 #define double                  XXdouble / / /
50
51 /*
52  * defined types
53  */
54 typedef uint8                   bool;
55 typedef uint8                   byte;
56 typedef struct  Func            Func;
57 typedef struct  G               G;
58 typedef struct  Gobuf           Gobuf;
59 typedef struct  SudoG           SudoG;
60 typedef struct  Mutex           Mutex;
61 typedef struct  M               M;
62 typedef struct  P               P;
63 typedef struct  SchedT  SchedT;
64 typedef struct  Note            Note;
65 typedef struct  Slice           Slice;
66 typedef struct  String          String;
67 typedef struct  FuncVal         FuncVal;
68 typedef struct  SigTab          SigTab;
69 typedef struct  MCache          MCache;
70 typedef struct  FixAlloc        FixAlloc;
71 typedef struct  Iface           Iface;
72 typedef struct  Itab            Itab;
73 typedef struct  InterfaceType   InterfaceType;
74 typedef struct  Eface           Eface;
75 typedef struct  Type            Type;
76 typedef struct  PtrType         PtrType;
77 typedef struct  ChanType        ChanType;
78 typedef struct  MapType         MapType;
79 typedef struct  Defer           Defer;
80 typedef struct  Panic           Panic;
81 typedef struct  Hmap            Hmap;
82 typedef struct  Hiter           Hiter;
83 typedef struct  Hchan           Hchan;
84 typedef struct  Complex64       Complex64;
85 typedef struct  Complex128      Complex128;
86 typedef struct  LibCall         LibCall;
87 typedef struct  WinCallbackContext      WinCallbackContext;
88 typedef struct  GCStats         GCStats;
89 typedef struct  LFNode          LFNode;
90 typedef struct  ParFor          ParFor;
91 typedef struct  ParForThread    ParForThread;
92 typedef struct  CgoMal          CgoMal;
93 typedef struct  PollDesc        PollDesc;
94 typedef struct  DebugVars       DebugVars;
95 typedef struct  ForceGCState    ForceGCState;
96 typedef struct  Stack           Stack;
97 typedef struct  Workbuf         Workbuf;
98
99 /*
100  * Per-CPU declaration.
101  *
102  * "extern register" is a special storage class implemented by 6c, 8c, etc.
103  * On the ARM, it is an actual register; elsewhere it is a slot in thread-
104  * local storage indexed by a pseudo-register TLS. See zasmhdr in
105  * src/cmd/dist/buildruntime.c for details, and be aware that the linker may
106  * make further OS-specific changes to the compiler's output. For example,
107  * 6l/linux rewrites 0(TLS) as -8(FS).
108  *
109  * Every C file linked into a Go program must include runtime.h so that the
110  * C compiler (6c, 8c, etc.) knows to avoid other uses of these dedicated
111  * registers. The Go compiler (6g, 8g, etc.) knows to avoid them.
112  */
113 extern  register        G*      g;
114
115 /*
116  * defined constants
117  */
118 enum
119 {
120         // G status
121         //
122         // If you add to this list, add to the list
123         // of "okay during garbage collection" status
124         // in mgc0.c too.
125         Gidle,                                 // 0
126         Grunnable,                             // 1 runnable and on a run queue
127         Grunning,                              // 2
128         Gsyscall,                              // 3
129         Gwaiting,                              // 4
130         Gmoribund_unused,                      // 5 currently unused, but hardcoded in gdb scripts
131         Gdead,                                 // 6
132         Genqueue,                              // 7 Only the Gscanenqueue is used.
133         Gcopystack,                            // 8 in this state when newstack is moving the stack
134         // the following encode that the GC is scanning the stack and what to do when it is done 
135         Gscan = 0x1000,                        // atomicstatus&~Gscan = the non-scan state,
136         // Gscanidle =     Gscan + Gidle,      // Not used. Gidle only used with newly malloced gs
137         Gscanrunnable = Gscan + Grunnable,     //  0x1001 When scanning complets make Grunnable (it is already on run queue)
138         Gscanrunning =  Gscan + Grunning,      //  0x1002 Used to tell preemption newstack routine to scan preempted stack.
139         Gscansyscall =  Gscan + Gsyscall,      //  0x1003 When scanning completes make is Gsyscall
140         Gscanwaiting =  Gscan + Gwaiting,      //  0x1004 When scanning completes make it Gwaiting
141         // Gscanmoribund_unused,               //  not possible
142         // Gscandead,                          //  not possible
143         Gscanenqueue = Gscan + Genqueue,       //  When scanning completes make it Grunnable and put on runqueue
144 };
145 enum
146 {
147         // P status
148         Pidle,
149         Prunning,
150         Psyscall,
151         Pgcstop,
152         Pdead,
153 };
154 enum
155 {
156         true    = 1,
157         false   = 0,
158 };
159 enum
160 {
161         PtrSize = sizeof(void*),
162 };
163 /*
164  * structures
165  */
166 struct  Mutex
167 {
168         // Futex-based impl treats it as uint32 key,
169         // while sema-based impl as M* waitm.
170         // Used to be a union, but unions break precise GC.
171         uintptr key;
172 };
173 struct  Note
174 {
175         // Futex-based impl treats it as uint32 key,
176         // while sema-based impl as M* waitm.
177         // Used to be a union, but unions break precise GC.
178         uintptr key;
179 };
180 struct String
181 {
182         byte*   str;
183         intgo   len;
184 };
185 struct FuncVal
186 {
187         void    (*fn)(void);
188         // variable-size, fn-specific data here
189 };
190 struct Iface
191 {
192         Itab*   tab;
193         void*   data;
194 };
195 struct Eface
196 {
197         Type*   type;
198         void*   data;
199 };
200 struct Complex64
201 {
202         float32 real;
203         float32 imag;
204 };
205 struct Complex128
206 {
207         float64 real;
208         float64 imag;
209 };
210
211 struct  Slice
212 {                               // must not move anything
213         byte*   array;          // actual data
214         uintgo  len;            // number of elements
215         uintgo  cap;            // allocated number of elements
216 };
217 struct  Gobuf
218 {
219         // The offsets of sp, pc, and g are known to (hard-coded in) libmach.
220         uintptr sp;
221         uintptr pc;
222         G*      g;
223         void*   ctxt; // this has to be a pointer so that GC scans it
224         uintreg ret;
225         uintptr lr;
226 };
227 // Known to compiler.
228 // Changes here must also be made in src/cmd/gc/select.c's selecttype.
229 struct  SudoG
230 {
231         G*      g;
232         uint32* selectdone;
233         SudoG*  next;
234         SudoG*  prev;
235         void*   elem;           // data element
236         int64   releasetime;
237         int32   nrelease;       // -1 for acquire
238         SudoG*  waitlink;       // G.waiting list
239 };
240 struct  GCStats
241 {
242         // the struct must consist of only uint64's,
243         // because it is casted to uint64[].
244         uint64  nhandoff;
245         uint64  nhandoffcnt;
246         uint64  nprocyield;
247         uint64  nosyield;
248         uint64  nsleep;
249 };
250
251 struct  LibCall
252 {
253         uintptr fn;
254         uintptr n;      // number of parameters
255         uintptr args;   // parameters
256         uintptr r1;     // return values
257         uintptr r2;
258         uintptr err;    // error number
259 };
260
261 // describes how to handle callback
262 struct  WinCallbackContext
263 {
264         void*   gobody;         // Go function to call
265         uintptr argsize;        // callback arguments size (in bytes)
266         uintptr restorestack;   // adjust stack on return by (in bytes) (386 only)
267         bool    cleanstack;
268 };
269
270 // Stack describes a Go execution stack.
271 // The bounds of the stack are exactly [lo, hi),
272 // with no implicit data structures on either side.
273 struct  Stack
274 {
275         uintptr lo;
276         uintptr hi;
277 };
278
279 struct  G
280 {
281         // Stack parameters.
282         // stack describes the actual stack memory: [stack.lo, stack.hi).
283         // stackguard0 is the stack pointer compared in the Go stack growth prologue.
284         // It is stack.lo+StackGuard normally, but can be StackPreempt to trigger a preemption.
285         // stackguard1 is the stack pointer compared in the C stack growth prologue.
286         // It is stack.lo+StackGuard on g0 and gsignal stacks.
287         // It is ~0 on other goroutine stacks, to trigger a call to morestackc (and crash).
288         Stack   stack;  // offset known to runtime/cgo
289         uintptr stackguard0;    // offset known to liblink
290         uintptr stackguard1;    // offset known to liblink
291
292         Panic*  panic;  // innermost panic - offset known to liblink
293         Defer*  defer;  // innermost defer
294         Gobuf   sched;
295         uintptr syscallsp;      // if status==Gsyscall, syscallsp = sched.sp to use during gc
296         uintptr syscallpc;      // if status==Gsyscall, syscallpc = sched.pc to use during gc
297         void*   param;          // passed parameter on wakeup
298         uint32  atomicstatus;
299         int64   goid;
300         int64   waitsince;      // approx time when the G become blocked
301         String  waitreason;     // if status==Gwaiting
302         G*      schedlink;
303         bool    issystem;       // do not output in stack dump, ignore in deadlock detector
304         bool    preempt;        // preemption signal, duplicates stackguard0 = StackPreempt
305         bool    paniconfault;   // panic (instead of crash) on unexpected fault address
306         bool    preemptscan;    // preempted g does scan for GC
307         bool    gcworkdone;     // debug: cleared at begining of gc work phase cycle, set by gcphasework, tested at end of cycle
308         bool    throwsplit;     // must not split stack
309         int8    raceignore;     // ignore race detection events
310         M*      m;              // for debuggers, but offset not hard-coded
311         M*      lockedm;
312         int32   sig;
313         Slice   writebuf;
314         uintptr sigcode0;
315         uintptr sigcode1;
316         uintptr sigpc;
317         uintptr gopc;           // pc of go statement that created this goroutine
318         uintptr racectx;
319         SudoG*  waiting;        // sudog structures this G is waiting on (that have a valid elem ptr)
320         uintptr end[];
321 };
322
323 struct  M
324 {
325         G*      g0;             // goroutine with scheduling stack
326         Gobuf   morebuf;        // gobuf arg to morestack
327
328         // Fields not known to debuggers.
329         uint64  procid;         // for debuggers, but offset not hard-coded
330         G*      gsignal;        // signal-handling G
331         uintptr tls[4];         // thread-local storage (for x86 extern register)
332         void    (*mstartfn)(void);
333         G*      curg;           // current running goroutine
334         G*      caughtsig;      // goroutine running during fatal signal
335         P*      p;              // attached P for executing Go code (nil if not executing Go code)
336         P*      nextp;
337         int32   id;
338         int32   mallocing;
339         int32   throwing;
340         int32   gcing;
341         int32   locks;
342         int32   softfloat;
343         int32   dying;
344         int32   profilehz;
345         int32   helpgc;
346         bool    spinning;       // M is out of work and is actively looking for work
347         bool    blocked;        // M is blocked on a Note
348         bool    inwb;           // M is executing a write barrier
349         int8    printlock;
350         uint32  fastrand;
351         uint64  ncgocall;       // number of cgo calls in total
352         int32   ncgo;           // number of cgo calls currently in progress
353         CgoMal* cgomal;
354         Note    park;
355         M*      alllink;        // on allm
356         M*      schedlink;
357         uint32  machport;       // Return address for Mach IPC (OS X)
358         MCache* mcache;
359         G*      lockedg;
360         uintptr createstack[32];// Stack that created this thread.
361         uint32  freglo[16];     // D[i] lsb and F[i]
362         uint32  freghi[16];     // D[i] msb and F[i+16]
363         uint32  fflag;          // floating point compare flags
364         uint32  locked;         // tracking for LockOSThread
365         M*      nextwaitm;      // next M waiting for lock
366         uintptr waitsema;       // semaphore for parking on locks
367         uint32  waitsemacount;
368         uint32  waitsemalock;
369         GCStats gcstats;
370         bool    needextram;
371         uint8   traceback;
372         bool    (*waitunlockf)(G*, void*);
373         void*   waitlock;
374         uintptr scalararg[4];   // scalar argument/return for mcall
375         void*   ptrarg[4];      // pointer argument/return for mcall
376 #ifdef GOOS_windows
377         uintptr thread;         // thread handle
378         // these are here because they are too large to be on the stack
379         // of low-level NOSPLIT functions.
380         LibCall libcall;
381         uintptr libcallpc;      // for cpu profiler
382         uintptr libcallsp;
383         G*      libcallg;
384 #endif
385 #ifdef GOOS_solaris
386         int32*  perrno;         // pointer to TLS errno
387         // these are here because they are too large to be on the stack
388         // of low-level NOSPLIT functions.
389         LibCall libcall;
390         struct MTs {
391                 int64   tv_sec;
392                 int64   tv_nsec;
393         } ts;
394         struct MScratch {
395                 uintptr v[6];
396         } scratch;
397 #endif
398 #ifdef GOOS_plan9
399         int8*   notesig;
400         byte*   errstr;
401 #endif
402         uintptr end[];
403 };
404
405 struct P
406 {
407         Mutex   lock;
408
409         int32   id;
410         uint32  status;         // one of Pidle/Prunning/...
411         P*      link;
412         uint32  schedtick;      // incremented on every scheduler call
413         uint32  syscalltick;    // incremented on every system call
414         M*      m;              // back-link to associated M (nil if idle)
415         MCache* mcache;
416         Defer*  deferpool[5];   // pool of available Defer structs of different sizes (see panic.c)
417
418         // Cache of goroutine ids, amortizes accesses to runtime·sched.goidgen.
419         uint64  goidcache;
420         uint64  goidcacheend;
421
422         // Queue of runnable goroutines.
423         uint32  runqhead;
424         uint32  runqtail;
425         G*      runq[256];
426
427         // Available G's (status == Gdead)
428         G*      gfree;
429         int32   gfreecnt;
430
431         byte    pad[64];
432 };
433
434 enum {
435         // The max value of GOMAXPROCS.
436         // There are no fundamental restrictions on the value.
437         MaxGomaxprocs = 1<<8,
438 };
439
440 struct  SchedT
441 {
442         Mutex   lock;
443
444         uint64  goidgen;
445
446         M*      midle;   // idle m's waiting for work
447         int32   nmidle;  // number of idle m's waiting for work
448         int32   nmidlelocked; // number of locked m's waiting for work
449         int32   mcount;  // number of m's that have been created
450         int32   maxmcount;      // maximum number of m's allowed (or die)
451
452         P*      pidle;  // idle P's
453         uint32  npidle;
454         uint32  nmspinning;
455
456         // Global runnable queue.
457         G*      runqhead;
458         G*      runqtail;
459         int32   runqsize;
460
461         // Global cache of dead G's.
462         Mutex   gflock;
463         G*      gfree;
464         int32   ngfree;
465
466         uint32  gcwaiting;      // gc is waiting to run
467         int32   stopwait;
468         Note    stopnote;
469         uint32  sysmonwait;
470         Note    sysmonnote;
471         uint64  lastpoll;
472
473         int32   profilehz;      // cpu profiling rate
474 };
475
476 // The m->locked word holds two pieces of state counting active calls to LockOSThread/lockOSThread.
477 // The low bit (LockExternal) is a boolean reporting whether any LockOSThread call is active.
478 // External locks are not recursive; a second lock is silently ignored.
479 // The upper bits of m->lockedcount record the nesting depth of calls to lockOSThread
480 // (counting up by LockInternal), popped by unlockOSThread (counting down by LockInternal).
481 // Internal locks can be recursive. For instance, a lock for cgo can occur while the main
482 // goroutine is holding the lock during the initialization phase.
483 enum
484 {
485         LockExternal = 1,
486         LockInternal = 2,
487 };
488
489 struct  SigTab
490 {
491         int32   flags;
492         int8    *name;
493 };
494 enum
495 {
496         SigNotify = 1<<0,       // let signal.Notify have signal, even if from kernel
497         SigKill = 1<<1,         // if signal.Notify doesn't take it, exit quietly
498         SigThrow = 1<<2,        // if signal.Notify doesn't take it, exit loudly
499         SigPanic = 1<<3,        // if the signal is from the kernel, panic
500         SigDefault = 1<<4,      // if the signal isn't explicitly requested, don't monitor it
501         SigHandling = 1<<5,     // our signal handler is registered
502         SigIgnored = 1<<6,      // the signal was ignored before we registered for it
503         SigGoExit = 1<<7,       // cause all runtime procs to exit (only used on Plan 9).
504 };
505
506 // Layout of in-memory per-function information prepared by linker
507 // See http://golang.org/s/go12symtab.
508 // Keep in sync with linker and with ../../libmach/sym.c
509 // and with package debug/gosym and with symtab.go in package runtime.
510 struct  Func
511 {
512         uintptr entry;  // start pc
513         int32   nameoff;// function name
514         
515         int32   args;   // in/out args size
516         int32   frame;  // legacy frame size; use pcsp if possible
517
518         int32   pcsp;
519         int32   pcfile;
520         int32   pcln;
521         int32   npcdata;
522         int32   nfuncdata;
523 };
524
525 // layout of Itab known to compilers
526 // allocated in non-garbage-collected memory
527 struct  Itab
528 {
529         InterfaceType*  inter;
530         Type*   type;
531         Itab*   link;
532         int32   bad;
533         int32   unused;
534         void    (*fun[])(void);
535 };
536
537 #ifdef GOOS_nacl
538 enum {
539    NaCl = 1,
540 };
541 #else
542 enum {
543    NaCl = 0,
544 };
545 #endif
546
547 #ifdef GOOS_windows
548 enum {
549    Windows = 1
550 };
551 #else
552 enum {
553    Windows = 0
554 };
555 #endif
556 #ifdef GOOS_solaris
557 enum {
558    Solaris = 1
559 };
560 #else
561 enum {
562    Solaris = 0
563 };
564 #endif
565 #ifdef GOOS_plan9
566 enum {
567    Plan9 = 1
568 };
569 #else
570 enum {
571    Plan9 = 0
572 };
573 #endif
574
575 // Lock-free stack node.
576 // Also known to export_test.go.
577 struct LFNode
578 {
579         uint64  next;
580         uintptr pushcnt;
581 };
582
583 // Parallel for descriptor.
584 struct ParFor
585 {
586         void (*body)(ParFor*, uint32);  // executed for each element
587         uint32 done;                    // number of idle threads
588         uint32 nthr;                    // total number of threads
589         uint32 nthrmax;                 // maximum number of threads
590         uint32 thrseq;                  // thread id sequencer
591         uint32 cnt;                     // iteration space [0, cnt)
592         void *ctx;                      // arbitrary user context
593         bool wait;                      // if true, wait while all threads finish processing,
594                                         // otherwise parfor may return while other threads are still working
595         ParForThread *thr;              // array of thread descriptors
596         uint32 pad;                     // to align ParForThread.pos for 64-bit atomic operations
597         // stats
598         uint64 nsteal;
599         uint64 nstealcnt;
600         uint64 nprocyield;
601         uint64 nosyield;
602         uint64 nsleep;
603 };
604
605 enum {
606         WorkbufSize     = 4*1024,
607 };
608 struct Workbuf
609 {
610         LFNode  node; // must be first
611         uintptr nobj;
612         byte*   obj[(WorkbufSize-sizeof(LFNode)-sizeof(uintptr))/PtrSize];
613 };
614
615 // Track memory allocated by code not written in Go during a cgo call,
616 // so that the garbage collector can see them.
617 struct CgoMal
618 {
619         CgoMal  *next;
620         void    *alloc;
621 };
622
623 // Holds variables parsed from GODEBUG env var.
624 struct DebugVars
625 {
626         int32   allocfreetrace;
627         int32   efence;
628         int32   gctrace;
629         int32   gcdead;
630         int32   scheddetail;
631         int32   schedtrace;
632         int32   scavenge;
633 };
634
635 // Indicates to write barrier and sychronization task to preform.
636 enum
637 {                               // Action               WB installation
638         GCoff = 0,              // stop and start       no wb
639         GCquiesce,              // stop and start       no wb
640         GCstw,                  // stop the ps          nop
641         GCscan,                 // scan the stacks prior to marking
642         GCmark,                 // mark use wbufs from GCscan and globals, scan the stacks, then go to GCtermination
643         GCmarktermination,      // mark termination detection. Allocate black, Ps help out GC
644         GCsweep,                // stop and start       nop
645 };
646
647 struct ForceGCState
648 {
649         Mutex   lock;
650         G*      g;
651         uint32  idle;
652 };
653
654 extern uint32 runtime·gcphase;
655 extern Mutex runtime·allglock;
656
657 /*
658  * defined macros
659  *    you need super-gopher-guru privilege
660  *    to add this list.
661  */
662 #define nelem(x)        (sizeof(x)/sizeof((x)[0]))
663 #define nil             ((void*)0)
664 #define offsetof(s,m)   (uint32)(&(((s*)0)->m))
665 #define ROUND(x, n)     (((x)+(n)-1)&~(uintptr)((n)-1)) /* all-caps to mark as macro: it evaluates n twice */
666
667 /*
668  * known to compiler
669  */
670 enum {
671         Structrnd = sizeof(uintreg),
672 };
673
674 byte*   runtime·startup_random_data;
675 uint32  runtime·startup_random_data_len;
676
677 int32   runtime·invalidptr;
678
679 enum {
680         // hashinit wants this many random bytes
681         HashRandomBytes = 32
682 };
683
684 uint32  runtime·readgstatus(G*);
685 void    runtime·casgstatus(G*, uint32, uint32);
686 bool    runtime·castogscanstatus(G*, uint32, uint32);
687 void    runtime·quiesce(G*);
688 bool    runtime·stopg(G*);
689 void    runtime·restartg(G*);
690 void    runtime·gcphasework(G*);
691
692 /*
693  * deferred subroutine calls
694  */
695 struct Defer
696 {
697         int32   siz;
698         bool    started;
699         uintptr argp;           // where args were copied from
700         uintptr pc;
701         FuncVal*        fn;
702         Panic*  panic;  // panic that is running defer
703         Defer*  link;
704 };
705
706 // argp used in Defer structs when there is no argp.
707 #define NoArgs ((uintptr)-1)
708
709 /*
710  * panics
711  */
712 struct Panic
713 {
714         void*   argp;   // pointer to arguments of deferred call run during panic; cannot move - known to liblink
715         Eface   arg;            // argument to panic
716         Panic*  link;           // link to earlier panic
717         bool    recovered;      // whether this panic is over
718         bool    aborted;        // the panic was aborted
719 };
720
721 /*
722  * stack traces
723  */
724 typedef struct Stkframe Stkframe;
725 typedef struct BitVector BitVector;
726 struct Stkframe
727 {
728         Func*   fn;     // function being run
729         uintptr pc;     // program counter within fn
730         uintptr continpc;       // program counter where execution can continue, or 0 if not
731         uintptr lr;     // program counter at caller aka link register
732         uintptr sp;     // stack pointer at pc
733         uintptr fp;     // stack pointer at caller aka frame pointer
734         uintptr varp;   // top of local variables
735         uintptr argp;   // pointer to function arguments
736         uintptr arglen; // number of bytes at argp
737         BitVector*      argmap; // force use of this argmap
738 };
739
740 enum
741 {
742         TraceRuntimeFrames = 1<<0, // include frames for internal runtime functions.
743         TraceTrap = 1<<1, // the initial PC, SP are from a trap, not a return PC from a call
744 };
745 intgo   runtime·gentraceback(uintptr, uintptr, uintptr, G*, intgo, uintptr*, intgo, bool(**)(Stkframe*, void*), void*, uintgo);
746 void    runtime·tracebackdefers(G*, bool(**)(Stkframe*, void*), void*);
747 void    runtime·traceback(uintptr pc, uintptr sp, uintptr lr, G* gp);
748 void    runtime·tracebacktrap(uintptr pc, uintptr sp, uintptr lr, G* gp);
749 void    runtime·tracebackothers(G*);
750 bool    runtime·haszeroargs(uintptr pc);
751 bool    runtime·topofstack(Func*);
752 enum
753 {
754         // The maximum number of frames we print for a traceback
755         TracebackMaxFrames = 100,
756 };
757
758 /*
759  * external data
760  */
761 extern  String  runtime·emptystring;
762 extern  G**     runtime·allg;
763 extern  Slice   runtime·allgs; // []*G
764 extern  uintptr runtime·allglen;
765 extern  G*      runtime·lastg;
766 extern  M*      runtime·allm;
767 extern  P*      runtime·allp[MaxGomaxprocs+1];
768 extern  int32   runtime·gomaxprocs;
769 extern  uint32  runtime·needextram;
770 extern  uint32  runtime·panicking;
771 extern  int8*   runtime·goos;
772 extern  int32   runtime·ncpu;
773 extern  bool    runtime·iscgo;
774 extern  void    (*runtime·sysargs)(int32, uint8**);
775 extern  uintptr runtime·maxstring;
776 extern  uint32  runtime·cpuid_ecx;
777 extern  uint32  runtime·cpuid_edx;
778 extern  DebugVars       runtime·debug;
779 extern  uintptr runtime·maxstacksize;
780 extern  Note    runtime·signote;
781 extern  ForceGCState    runtime·forcegc;
782 extern  SchedT  runtime·sched;
783 extern  int32           runtime·newprocs;
784
785 /*
786  * common functions and data
787  */
788 int32   runtime·strcmp(byte*, byte*);
789 int32   runtime·strncmp(byte*, byte*, uintptr);
790 byte*   runtime·strstr(byte*, byte*);
791 intgo   runtime·findnull(byte*);
792 intgo   runtime·findnullw(uint16*);
793 void    runtime·dump(byte*, int32);
794 int32   runtime·runetochar(byte*, int32);
795 int32   runtime·charntorune(int32*, uint8*, int32);
796
797
798 /*
799  * This macro is used when writing C functions
800  * called as if they were Go functions.
801  * Passed the address of a result before a return statement,
802  * it makes sure the result has been flushed to memory
803  * before the return.
804  *
805  * It is difficult to write such functions portably, because
806  * of the varying requirements on the alignment of the
807  * first output value. Almost all code should write such
808  * functions in .goc files, where goc2c (part of cmd/dist)
809  * can arrange the correct alignment for the target system.
810  * Goc2c also takes care of conveying to the garbage collector
811  * which parts of the argument list are inputs vs outputs.
812  *
813  * Therefore, do NOT use this macro if at all possible.
814  */ 
815 #define FLUSH(x)        USED(x)
816
817 /*
818  * GoOutput is a type with the same alignment requirements as the
819  * initial output argument from a Go function. Only for use in cases
820  * where using goc2c is not possible. See comment on FLUSH above.
821  */
822 typedef uint64 GoOutput;
823
824 void    runtime·gogo(Gobuf*);
825 void    runtime·gostartcall(Gobuf*, void(*)(void), void*);
826 void    runtime·gostartcallfn(Gobuf*, FuncVal*);
827 void    runtime·gosave(Gobuf*);
828 void    runtime·goargs(void);
829 void    runtime·goenvs(void);
830 void    runtime·goenvs_unix(void);
831 void*   runtime·getu(void);
832 void    runtime·throw(int8*);
833 bool    runtime·canpanic(G*);
834 void    runtime·prints(int8*);
835 void    runtime·printf(int8*, ...);
836 void    runtime·snprintf(byte*, int32, int8*, ...);
837 byte*   runtime·mchr(byte*, byte, byte*);
838 int32   runtime·mcmp(byte*, byte*, uintptr);
839 void    runtime·memmove(void*, void*, uintptr);
840 String  runtime·catstring(String, String);
841 String  runtime·gostring(byte*);
842 Slice   runtime·makeStringSlice(intgo);
843 String  runtime·gostringn(byte*, intgo);
844 Slice   runtime·gobytes(byte*, intgo);
845 String  runtime·gostringnocopy(byte*);
846 String  runtime·gostringw(uint16*);
847 void    runtime·initsig(void);
848 void    runtime·sigenable(uint32 sig);
849 void    runtime·sigdisable(uint32 sig);
850 int32   runtime·gotraceback(bool *crash);
851 void    runtime·goroutineheader(G*);
852 int32   runtime·open(int8*, int32, int32);
853 int32   runtime·read(int32, void*, int32);
854 int32   runtime·write(uintptr, void*, int32); // use uintptr to accommodate windows.
855 int32   runtime·close(int32);
856 int32   runtime·mincore(void*, uintptr, byte*);
857 void    runtime·jmpdefer(FuncVal*, uintptr);
858 void    runtime·exit1(int32);
859 void    runtime·ready(G*);
860 byte*   runtime·getenv(int8*);
861 int32   runtime·atoi(byte*);
862 void    runtime·newosproc(M *mp, void *stk);
863 void    runtime·mstart(void);
864 G*      runtime·malg(int32);
865 void    runtime·asminit(void);
866 void    runtime·mpreinit(M*);
867 void    runtime·minit(void);
868 void    runtime·unminit(void);
869 void    runtime·signalstack(byte*, int32);
870 void    runtime·tracebackinit(void);
871 void    runtime·symtabinit(void);
872 Func*   runtime·findfunc(uintptr);
873 int32   runtime·funcline(Func*, uintptr, String*);
874 int32   runtime·funcspdelta(Func*, uintptr);
875 int8*   runtime·funcname(Func*);
876 int32   runtime·pcdatavalue(Func*, int32, uintptr);
877 void    runtime·stackinit(void);
878 Stack   runtime·stackalloc(uint32);
879 void    runtime·stackfree(Stack);
880 void    runtime·shrinkstack(G*);
881 void    runtime·shrinkfinish(void);
882 MCache* runtime·allocmcache(void);
883 void    runtime·freemcache(MCache*);
884 void    runtime·mallocinit(void);
885 void    runtime·gcinit(void);
886 void*   runtime·mallocgc(uintptr size, Type* typ, uint32 flag);
887 void    runtime·runpanic(Panic*);
888 uintptr runtime·getcallersp(void*);
889 int32   runtime·mcount(void);
890 int32   runtime·gcount(void);
891 void    runtime·mcall(void(**)(G*));
892 void    runtime·onM(void(**)(void));
893 void    runtime·onMsignal(void(**)(void));
894 uint32  runtime·fastrand1(void);
895 void    runtime·rewindmorestack(Gobuf*);
896 int32   runtime·timediv(int64, int32, int32*);
897 int32   runtime·round2(int32 x); // round x up to a power of 2.
898
899 // atomic operations
900 bool    runtime·cas(uint32*, uint32, uint32);
901 bool    runtime·cas64(uint64*, uint64, uint64);
902 bool    runtime·casp(void**, void*, void*);
903 bool    runtime·casuintptr(uintptr*, uintptr, uintptr);
904 // Don't confuse with XADD x86 instruction,
905 // this one is actually 'addx', that is, add-and-fetch.
906 uint32  runtime·xadd(uint32 volatile*, int32);
907 uint64  runtime·xadd64(uint64 volatile*, int64);
908 uint32  runtime·xchg(uint32 volatile*, uint32);
909 uint64  runtime·xchg64(uint64 volatile*, uint64);
910 void*   runtime·xchgp(void* volatile*, void*);
911 uint32  runtime·atomicload(uint32 volatile*);
912 void    runtime·atomicstore(uint32 volatile*, uint32);
913 void    runtime·atomicstore64(uint64 volatile*, uint64);
914 uint64  runtime·atomicload64(uint64 volatile*);
915 void*   runtime·atomicloadp(void* volatile*);
916 uintptr runtime·atomicloaduintptr(uintptr volatile*);
917 void    runtime·atomicstorep(void* volatile*, void*);
918 void    runtime·atomicstoreuintptr(uintptr volatile*, uintptr);
919 void    runtime·atomicor8(byte volatile*, byte);
920
921 void    runtime·setg(G*);
922 void    runtime·newextram(void);
923 void    runtime·exit(int32);
924 void    runtime·breakpoint(void);
925 void    runtime·gosched_m(G*);
926 void    runtime·schedtrace(bool);
927 void    runtime·park(bool(*)(G*, void*), void*, String);
928 void    runtime·parkunlock(Mutex*, String);
929 void    runtime·tsleep(int64, String);
930 M*      runtime·newm(void);
931 void    runtime·goexit(void);
932 void    runtime·asmcgocall(void (*fn)(void*), void*);
933 int32   runtime·asmcgocall_errno(void (*fn)(void*), void*);
934 void    runtime·entersyscall(void);
935 void    runtime·reentersyscall(uintptr, uintptr);
936 void    runtime·entersyscallblock(void);
937 void    runtime·exitsyscall(void);
938 G*      runtime·newproc1(FuncVal*, byte*, int32, int32, void*);
939 bool    runtime·sigsend(int32 sig);
940 intgo   runtime·callers(intgo, uintptr*, intgo);
941 intgo   runtime·gcallers(G*, intgo, uintptr*, intgo);
942 int64   runtime·nanotime(void);        // monotonic time
943 int64   runtime·unixnanotime(void); // real time, can skip
944 void    runtime·dopanic(int32);
945 void    runtime·startpanic(void);
946 void    runtime·freezetheworld(void);
947 void    runtime·sigprof(uint8 *pc, uint8 *sp, uint8 *lr, G *gp, M *mp);
948 void    runtime·resetcpuprofiler(int32);
949 void    runtime·setcpuprofilerate(int32);
950 void    runtime·usleep(uint32);
951 int64   runtime·cputicks(void);
952 int64   runtime·tickspersecond(void);
953 void    runtime·blockevent(int64, intgo);
954 G*      runtime·netpoll(bool);
955 void    runtime·netpollready(G**, PollDesc*, int32);
956 uintptr runtime·netpollfd(PollDesc*);
957 void**  runtime·netpolluser(PollDesc*);
958 bool    runtime·netpollclosing(PollDesc*);
959 void    runtime·netpolllock(PollDesc*);
960 void    runtime·netpollunlock(PollDesc*);
961 void    runtime·crash(void);
962 void    runtime·parsedebugvars(void);
963 void*   runtime·funcdata(Func*, int32);
964 void    runtime·setmaxthreads_m(void);
965 G*      runtime·timejump(void);
966 void    runtime·iterate_itabs(void (**callback)(Itab*));
967 void    runtime·iterate_finq(void (*callback)(FuncVal*, byte*, uintptr, Type*, PtrType*));
968
969 #pragma varargck        argpos  runtime·printf 1
970 #pragma varargck        type    "c"     int32
971 #pragma varargck        type    "d"     int32
972 #pragma varargck        type    "d"     uint32
973 #pragma varargck        type    "D"     int64
974 #pragma varargck        type    "D"     uint64
975 #pragma varargck        type    "x"     int32
976 #pragma varargck        type    "x"     uint32
977 #pragma varargck        type    "X"     int64
978 #pragma varargck        type    "X"     uint64
979 #pragma varargck        type    "p"     void*
980 #pragma varargck        type    "p"     uintptr
981 #pragma varargck        type    "s"     int8*
982 #pragma varargck        type    "s"     uint8*
983 #pragma varargck        type    "S"     String
984
985 void    runtime·stoptheworld(void);
986 void    runtime·starttheworld(void);
987 extern uint32 runtime·worldsema;
988
989 /*
990  * mutual exclusion locks.  in the uncontended case,
991  * as fast as spin locks (just a few user-level instructions),
992  * but on the contention path they sleep in the kernel.
993  * a zeroed Mutex is unlocked (no need to initialize each lock).
994  */
995 void    runtime·lock(Mutex*);
996 void    runtime·unlock(Mutex*);
997
998 /*
999  * sleep and wakeup on one-time events.
1000  * before any calls to notesleep or notewakeup,
1001  * must call noteclear to initialize the Note.
1002  * then, exactly one thread can call notesleep
1003  * and exactly one thread can call notewakeup (once).
1004  * once notewakeup has been called, the notesleep
1005  * will return.  future notesleep will return immediately.
1006  * subsequent noteclear must be called only after
1007  * previous notesleep has returned, e.g. it's disallowed
1008  * to call noteclear straight after notewakeup.
1009  *
1010  * notetsleep is like notesleep but wakes up after
1011  * a given number of nanoseconds even if the event
1012  * has not yet happened.  if a goroutine uses notetsleep to
1013  * wake up early, it must wait to call noteclear until it
1014  * can be sure that no other goroutine is calling
1015  * notewakeup.
1016  *
1017  * notesleep/notetsleep are generally called on g0,
1018  * notetsleepg is similar to notetsleep but is called on user g.
1019  */
1020 void    runtime·noteclear(Note*);
1021 void    runtime·notesleep(Note*);
1022 void    runtime·notewakeup(Note*);
1023 bool    runtime·notetsleep(Note*, int64);  // false - timeout
1024 bool    runtime·notetsleepg(Note*, int64);  // false - timeout
1025
1026 /*
1027  * low-level synchronization for implementing the above
1028  */
1029 uintptr runtime·semacreate(void);
1030 int32   runtime·semasleep(int64);
1031 void    runtime·semawakeup(M*);
1032 // or
1033 void    runtime·futexsleep(uint32*, uint32, int64);
1034 void    runtime·futexwakeup(uint32*, uint32);
1035
1036 /*
1037  * Mutex-free stack.
1038  * Initialize uint64 head to 0, compare with 0 to test for emptiness.
1039  * The stack does not keep pointers to nodes,
1040  * so they can be garbage collected if there are no other pointers to nodes.
1041  */
1042 void    runtime·lfstackpush(uint64 *head, LFNode *node);
1043 LFNode* runtime·lfstackpop(uint64 *head);
1044
1045 /*
1046  * Parallel for over [0, n).
1047  * body() is executed for each iteration.
1048  * nthr - total number of worker threads.
1049  * ctx - arbitrary user context.
1050  * if wait=true, threads return from parfor() when all work is done;
1051  * otherwise, threads can return while other threads are still finishing processing.
1052  */
1053 ParFor* runtime·parforalloc(uint32 nthrmax);
1054 void    runtime·parforsetup(ParFor *desc, uint32 nthr, uint32 n, void *ctx, bool wait, void (*body)(ParFor*, uint32));
1055 void    runtime·parfordo(ParFor *desc);
1056 void    runtime·parforiters(ParFor*, uintptr, uintptr*, uintptr*);
1057
1058 /*
1059  * low level C-called
1060  */
1061 // for mmap, we only pass the lower 32 bits of file offset to the 
1062 // assembly routine; the higher bits (if required), should be provided
1063 // by the assembly routine as 0.
1064 uint8*  runtime·mmap(byte*, uintptr, int32, int32, int32, uint32);
1065 void    runtime·munmap(byte*, uintptr);
1066 void    runtime·madvise(byte*, uintptr, int32);
1067 void    runtime·memclr(byte*, uintptr);
1068 void    runtime·setcallerpc(void*, void*);
1069 void*   runtime·getcallerpc(void*);
1070 void    runtime·printbool(bool);
1071 void    runtime·printbyte(int8);
1072 void    runtime·printfloat(float64);
1073 void    runtime·printint(int64);
1074 void    runtime·printiface(Iface);
1075 void    runtime·printeface(Eface);
1076 void    runtime·printstring(String);
1077 void    runtime·printpc(void*);
1078 void    runtime·printpointer(void*);
1079 void    runtime·printuint(uint64);
1080 void    runtime·printhex(uint64);
1081 void    runtime·printslice(Slice);
1082 void    runtime·printcomplex(Complex128);
1083
1084 /*
1085  * runtime go-called
1086  */
1087 void    runtime·gopanic(Eface);
1088 void    runtime·panicindex(void);
1089 void    runtime·panicslice(void);
1090 void    runtime·panicdivide(void);
1091
1092 /*
1093  * runtime c-called (but written in Go)
1094  */
1095 void    runtime·printany(Eface);
1096 void    runtime·newTypeAssertionError(String*, String*, String*, String*, Eface*);
1097 void    runtime·fadd64c(uint64, uint64, uint64*);
1098 void    runtime·fsub64c(uint64, uint64, uint64*);
1099 void    runtime·fmul64c(uint64, uint64, uint64*);
1100 void    runtime·fdiv64c(uint64, uint64, uint64*);
1101 void    runtime·fneg64c(uint64, uint64*);
1102 void    runtime·f32to64c(uint32, uint64*);
1103 void    runtime·f64to32c(uint64, uint32*);
1104 void    runtime·fcmp64c(uint64, uint64, int32*, bool*);
1105 void    runtime·fintto64c(int64, uint64*);
1106 void    runtime·f64tointc(uint64, int64*, bool*);
1107
1108 /*
1109  * wrapped for go users
1110  */
1111 float64 runtime·Inf(int32 sign);
1112 float64 runtime·NaN(void);
1113 float32 runtime·float32frombits(uint32 i);
1114 uint32  runtime·float32tobits(float32 f);
1115 float64 runtime·float64frombits(uint64 i);
1116 uint64  runtime·float64tobits(float64 f);
1117 float64 runtime·frexp(float64 d, int32 *ep);
1118 bool    runtime·isInf(float64 f, int32 sign);
1119 bool    runtime·isNaN(float64 f);
1120 float64 runtime·ldexp(float64 d, int32 e);
1121 float64 runtime·modf(float64 d, float64 *ip);
1122 void    runtime·semacquire(uint32*, bool);
1123 void    runtime·semrelease(uint32*);
1124 int32   runtime·gomaxprocsfunc(int32 n);
1125 void    runtime·procyield(uint32);
1126 void    runtime·osyield(void);
1127 void    runtime·lockOSThread(void);
1128 void    runtime·unlockOSThread(void);
1129
1130 void    runtime·writebarrierptr_nostore(void*, void*);
1131
1132 bool    runtime·showframe(Func*, G*);
1133 void    runtime·printcreatedby(G*);
1134
1135 void    runtime·ifaceE2I(InterfaceType*, Eface, Iface*);
1136 bool    runtime·ifaceE2I2(InterfaceType*, Eface, Iface*);
1137 uintptr runtime·memlimit(void);
1138
1139 // float.c
1140 extern float64 runtime·nan;
1141 extern float64 runtime·posinf;
1142 extern float64 runtime·neginf;
1143 extern uint64 ·nan;
1144 extern uint64 ·posinf;
1145 extern uint64 ·neginf;
1146 #define ISNAN(f) ((f) != (f))
1147
1148 enum
1149 {
1150         UseSpanType = 1,
1151 };