github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/cmd/ld/dwarf.c (about)

     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  // TODO/NICETOHAVE:
     6  //   - eliminate DW_CLS_ if not used
     7  //   - package info in compilation units
     8  //   - assign global variables and types to their packages
     9  //   - gdb uses c syntax, meaning clumsy quoting is needed for go identifiers. eg
    10  //     ptype struct '[]uint8' and qualifiers need to be quoted away
    11  //   - lexical scoping is lost, so gdb gets confused as to which 'main.i' you mean.
    12  //   - file:line info for variables
    13  //   - make strings a typedef so prettyprinters can see the underlying string type
    14  //
    15  #include	"l.h"
    16  #include	"lib.h"
    17  #include	"../ld/dwarf.h"
    18  #include	"../ld/dwarf_defs.h"
    19  #include	"../ld/elf.h"
    20  #include	"../ld/macho.h"
    21  #include	"../ld/pe.h"
    22  #include	"../../pkg/runtime/typekind.h"
    23  
    24  /*
    25   * Offsets and sizes of the debug_* sections in the cout file.
    26   */
    27  
    28  static vlong abbrevo;
    29  static vlong abbrevsize;
    30  static Sym*  abbrevsym;
    31  static vlong abbrevsympos;
    32  static vlong lineo;
    33  static vlong linesize;
    34  static Sym*  linesym;
    35  static vlong linesympos;
    36  static vlong infoo;	// also the base for DWDie->offs and reference attributes.
    37  static vlong infosize;
    38  static Sym*  infosym;
    39  static vlong infosympos;
    40  static vlong frameo;
    41  static vlong framesize;
    42  static vlong pubnameso;
    43  static vlong pubnamessize;
    44  static vlong pubtypeso;
    45  static vlong pubtypessize;
    46  static vlong arangeso;
    47  static vlong arangessize;
    48  static vlong gdbscripto;
    49  static vlong gdbscriptsize;
    50  
    51  static Sym *infosec;
    52  static vlong inforeloco;
    53  static vlong inforelocsize;
    54  
    55  static Sym *arangessec;
    56  static vlong arangesreloco;
    57  static vlong arangesrelocsize;
    58  
    59  static Sym *linesec;
    60  static vlong linereloco;
    61  static vlong linerelocsize;
    62  
    63  static char  gdbscript[1024];
    64  
    65  /*
    66   *  Basic I/O
    67   */
    68  
    69  static void
    70  addrput(vlong addr)
    71  {
    72  	switch(PtrSize) {
    73  	case 4:
    74  		LPUT(addr);
    75  		break;
    76  	case 8:
    77  		VPUT(addr);
    78  		break;
    79  	}
    80  }
    81  
    82  static int
    83  uleb128enc(uvlong v, char* dst)
    84  {
    85  	uint8 c, len;
    86  
    87  	len = 0;
    88  	do {
    89  		c = v & 0x7f;
    90  		v >>= 7;
    91  		if (v)
    92  			c |= 0x80;
    93  		if (dst)
    94  			*dst++ = c;
    95  		len++;
    96  	} while (c & 0x80);
    97  	return len;
    98  };
    99  
   100  static int
   101  sleb128enc(vlong v, char *dst)
   102  {
   103  	uint8 c, s, len;
   104  
   105  	len = 0;
   106  	do {
   107  		c = v & 0x7f;
   108  		s = v & 0x40;
   109  		v >>= 7;
   110  		if ((v != -1 || !s) && (v != 0 || s))
   111  			c |= 0x80;
   112  		if (dst)
   113  			*dst++ = c;
   114  		len++;
   115  	} while(c & 0x80);
   116  	return len;
   117  }
   118  
   119  static void
   120  uleb128put(vlong v)
   121  {
   122  	char buf[10];
   123  	strnput(buf, uleb128enc(v, buf));
   124  }
   125  
   126  static void
   127  sleb128put(vlong v)
   128  {
   129  	char buf[10];
   130  	strnput(buf, sleb128enc(v, buf));
   131  }
   132  
   133  /*
   134   * Defining Abbrevs.  This is hardcoded, and there will be
   135   * only a handful of them.  The DWARF spec places no restriction on
   136   * the ordering of atributes in the Abbrevs and DIEs, and we will
   137   * always write them out in the order of declaration in the abbrev.
   138   * This implementation relies on tag, attr < 127, so they serialize as
   139   * a char.  Higher numbered user-defined tags or attributes can be used
   140   * for storing internal data but won't be serialized.
   141   */
   142  typedef struct DWAttrForm DWAttrForm;
   143  struct DWAttrForm {
   144  	uint8 attr;
   145  	uint8 form;
   146  };
   147  
   148  // Index into the abbrevs table below.
   149  // Keep in sync with ispubname() and ispubtype() below.
   150  // ispubtype considers >= NULLTYPE public
   151  enum
   152  {
   153  	DW_ABRV_NULL,
   154  	DW_ABRV_COMPUNIT,
   155  	DW_ABRV_FUNCTION,
   156  	DW_ABRV_VARIABLE,
   157  	DW_ABRV_AUTO,
   158  	DW_ABRV_PARAM,
   159  	DW_ABRV_STRUCTFIELD,
   160  	DW_ABRV_FUNCTYPEPARAM,
   161  	DW_ABRV_DOTDOTDOT,
   162  	DW_ABRV_ARRAYRANGE,
   163  	DW_ABRV_NULLTYPE,
   164  	DW_ABRV_BASETYPE,
   165  	DW_ABRV_ARRAYTYPE,
   166  	DW_ABRV_CHANTYPE,
   167  	DW_ABRV_FUNCTYPE,
   168  	DW_ABRV_IFACETYPE,
   169  	DW_ABRV_MAPTYPE,
   170  	DW_ABRV_PTRTYPE,
   171  	DW_ABRV_BARE_PTRTYPE, // only for void*, no DW_AT_type attr to please gdb 6.
   172  	DW_ABRV_SLICETYPE,
   173  	DW_ABRV_STRINGTYPE,
   174  	DW_ABRV_STRUCTTYPE,
   175  	DW_ABRV_TYPEDECL,
   176  	DW_NABRV
   177  };
   178  
   179  typedef struct DWAbbrev DWAbbrev;
   180  static struct DWAbbrev {
   181  	uint8 tag;
   182  	uint8 children;
   183  	DWAttrForm attr[30];
   184  } abbrevs[DW_NABRV] = {
   185  	/* The mandatory DW_ABRV_NULL entry. */
   186  	{ 0 },
   187  	/* COMPUNIT */
   188  	{
   189  		DW_TAG_compile_unit, DW_CHILDREN_yes,
   190  		DW_AT_name,	 DW_FORM_string,
   191  		DW_AT_language,	 DW_FORM_data1,
   192  		DW_AT_low_pc,	 DW_FORM_addr,
   193  		DW_AT_high_pc,	 DW_FORM_addr,
   194  		DW_AT_stmt_list, DW_FORM_data4,
   195  		0, 0
   196  	},
   197  	/* FUNCTION */
   198  	{
   199  		DW_TAG_subprogram, DW_CHILDREN_yes,
   200  		DW_AT_name,	 DW_FORM_string,
   201  		DW_AT_low_pc,	 DW_FORM_addr,
   202  		DW_AT_high_pc,	 DW_FORM_addr,
   203  		DW_AT_external,	 DW_FORM_flag,
   204  		0, 0
   205  	},
   206  	/* VARIABLE */
   207  	{
   208  		DW_TAG_variable, DW_CHILDREN_no,
   209  		DW_AT_name,	 DW_FORM_string,
   210  		DW_AT_location,	 DW_FORM_block1,
   211  		DW_AT_type,	 DW_FORM_ref_addr,
   212  		DW_AT_external,	 DW_FORM_flag,
   213  		0, 0
   214  	},
   215  	/* AUTO */
   216  	{
   217  		DW_TAG_variable, DW_CHILDREN_no,
   218  		DW_AT_name,	 DW_FORM_string,
   219  		DW_AT_location,	 DW_FORM_block1,
   220  		DW_AT_type,	 DW_FORM_ref_addr,
   221  		0, 0
   222  	},
   223  	/* PARAM */
   224  	{
   225  		DW_TAG_formal_parameter, DW_CHILDREN_no,
   226  		DW_AT_name,	 DW_FORM_string,
   227  		DW_AT_location,	 DW_FORM_block1,
   228  		DW_AT_type,	 DW_FORM_ref_addr,
   229  		0, 0
   230  	},
   231  	/* STRUCTFIELD */
   232  	{
   233  		DW_TAG_member,	DW_CHILDREN_no,
   234  		DW_AT_name,	DW_FORM_string,
   235  		DW_AT_data_member_location, DW_FORM_block1,
   236  		DW_AT_type,	 DW_FORM_ref_addr,
   237  		0, 0
   238  	},
   239  	/* FUNCTYPEPARAM */
   240  	{
   241  		DW_TAG_formal_parameter, DW_CHILDREN_no,
   242  		// No name!
   243  		DW_AT_type,	 DW_FORM_ref_addr,
   244  		0, 0
   245  	},
   246  
   247  	/* DOTDOTDOT */
   248  	{
   249  		DW_TAG_unspecified_parameters, DW_CHILDREN_no,
   250  		0, 0
   251  	},
   252  	/* ARRAYRANGE */
   253  	{
   254  		DW_TAG_subrange_type, DW_CHILDREN_no,
   255  		// No name!
   256  		DW_AT_type,	 DW_FORM_ref_addr,
   257  		DW_AT_upper_bound, DW_FORM_data1,
   258  		0, 0
   259  	},
   260  
   261  	// Below here are the types considered public by ispubtype
   262  	/* NULLTYPE */
   263  	{
   264  		DW_TAG_unspecified_type, DW_CHILDREN_no,
   265  		DW_AT_name,	DW_FORM_string,
   266  		0, 0
   267  	},
   268  	/* BASETYPE */
   269  	{
   270  		DW_TAG_base_type, DW_CHILDREN_no,
   271  		DW_AT_name,	 DW_FORM_string,
   272  		DW_AT_encoding,	 DW_FORM_data1,
   273  		DW_AT_byte_size, DW_FORM_data1,
   274  		0, 0
   275  	},
   276  	/* ARRAYTYPE */
   277  	// child is subrange with upper bound
   278  	{
   279  		DW_TAG_array_type, DW_CHILDREN_yes,
   280  		DW_AT_name,	DW_FORM_string,
   281  		DW_AT_type,	DW_FORM_ref_addr,
   282  		DW_AT_byte_size, DW_FORM_udata,
   283  		0, 0
   284  	},
   285  
   286  	/* CHANTYPE */
   287  	{
   288  		DW_TAG_typedef, DW_CHILDREN_no,
   289  		DW_AT_name,	DW_FORM_string,
   290  		DW_AT_type,	DW_FORM_ref_addr,
   291  		0, 0
   292  	},
   293  
   294  	/* FUNCTYPE */
   295  	{
   296  		DW_TAG_subroutine_type, DW_CHILDREN_yes,
   297  		DW_AT_name,	DW_FORM_string,
   298  //		DW_AT_type,	DW_FORM_ref_addr,
   299  		0, 0
   300  	},
   301  
   302  	/* IFACETYPE */
   303  	{
   304  		DW_TAG_typedef, DW_CHILDREN_yes,
   305  		DW_AT_name,	 DW_FORM_string,
   306  		DW_AT_type,	DW_FORM_ref_addr,
   307  		0, 0
   308  	},
   309  
   310  	/* MAPTYPE */
   311  	{
   312  		DW_TAG_typedef, DW_CHILDREN_no,
   313  		DW_AT_name,	DW_FORM_string,
   314  		DW_AT_type,	DW_FORM_ref_addr,
   315  		0, 0
   316  	},
   317  
   318  	/* PTRTYPE */
   319  	{
   320  		DW_TAG_pointer_type, DW_CHILDREN_no,
   321  		DW_AT_name,	DW_FORM_string,
   322  		DW_AT_type,	DW_FORM_ref_addr,
   323  		0, 0
   324  	},
   325  	/* BARE_PTRTYPE */
   326  	{
   327  		DW_TAG_pointer_type, DW_CHILDREN_no,
   328  		DW_AT_name,	DW_FORM_string,
   329  		0, 0
   330  	},
   331  
   332  	/* SLICETYPE */
   333  	{
   334  		DW_TAG_structure_type, DW_CHILDREN_yes,
   335  		DW_AT_name,	DW_FORM_string,
   336  		DW_AT_byte_size, DW_FORM_udata,
   337  		0, 0
   338  	},
   339  
   340  	/* STRINGTYPE */
   341  	{
   342  		DW_TAG_structure_type, DW_CHILDREN_yes,
   343  		DW_AT_name,	DW_FORM_string,
   344  		DW_AT_byte_size, DW_FORM_udata,
   345  		0, 0
   346  	},
   347  
   348  	/* STRUCTTYPE */
   349  	{
   350  		DW_TAG_structure_type, DW_CHILDREN_yes,
   351  		DW_AT_name,	DW_FORM_string,
   352  		DW_AT_byte_size, DW_FORM_udata,
   353  		0, 0
   354  	},
   355  
   356  	/* TYPEDECL */
   357  	{
   358  		DW_TAG_typedef, DW_CHILDREN_no,
   359  		DW_AT_name,	DW_FORM_string,
   360  		DW_AT_type,	DW_FORM_ref_addr,
   361  		0, 0
   362  	},
   363  };
   364  
   365  static void
   366  writeabbrev(void)
   367  {
   368  	int i, n;
   369  
   370  	abbrevo = cpos();
   371  	for (i = 1; i < DW_NABRV; i++) {
   372  		// See section 7.5.3
   373  		uleb128put(i);
   374  		uleb128put(abbrevs[i].tag);
   375  		cput(abbrevs[i].children);
   376  		// 0 is not a valid attr or form, and DWAbbrev.attr is
   377  		// 0-terminated, so we can treat it as a string
   378  		n = strlen((char*)abbrevs[i].attr) / 2;
   379  		strnput((char*)abbrevs[i].attr,
   380  			(n+1) * sizeof(DWAttrForm));
   381  	}
   382  	cput(0);
   383  	abbrevsize = cpos() - abbrevo;
   384  }
   385  
   386  /*
   387   * Debugging Information Entries and their attributes.
   388   */
   389  
   390  enum
   391  {
   392  	HASHSIZE = 107
   393  };
   394  
   395  static uint32
   396  hashstr(char* s)
   397  {
   398  	uint32 h;
   399  
   400  	h = 0;
   401  	while (*s)
   402  		h = h+h+h + *s++;
   403  	return h % HASHSIZE;
   404  }
   405  
   406  // For DW_CLS_string and _block, value should contain the length, and
   407  // data the data, for _reference, value is 0 and data is a DWDie* to
   408  // the referenced instance, for all others, value is the whole thing
   409  // and data is null.
   410  
   411  typedef struct DWAttr DWAttr;
   412  struct DWAttr {
   413  	DWAttr *link;
   414  	uint8 atr;  // DW_AT_
   415  	uint8 cls;  // DW_CLS_
   416  	vlong value;
   417  	char *data;
   418  };
   419  
   420  typedef struct DWDie DWDie;
   421  struct DWDie {
   422  	int abbrev;
   423  	DWDie *link;
   424  	DWDie *child;
   425  	DWAttr *attr;
   426  	// offset into .debug_info section, i.e relative to
   427  	// infoo. only valid after call to putdie()
   428  	vlong offs;
   429  	DWDie **hash;  // optional index of children by name, enabled by mkindex()
   430  	DWDie *hlink;  // bucket chain in parent's index
   431  };
   432  
   433  /*
   434   * Root DIEs for compilation units, types and global variables.
   435   */
   436  
   437  static DWDie dwroot;
   438  static DWDie dwtypes;
   439  static DWDie dwglobals;
   440  
   441  static DWAttr*
   442  newattr(DWDie *die, uint8 attr, int cls, vlong value, char *data)
   443  {
   444  	DWAttr *a;
   445  
   446  	a = mal(sizeof *a);
   447  	a->link = die->attr;
   448  	die->attr = a;
   449  	a->atr = attr;
   450  	a->cls = cls;
   451  	a->value = value;
   452  	a->data = data;
   453  	return a;
   454  }
   455  
   456  // Each DIE (except the root ones) has at least 1 attribute: its
   457  // name. getattr moves the desired one to the front so
   458  // frequently searched ones are found faster.
   459  static DWAttr*
   460  getattr(DWDie *die, uint8 attr)
   461  {
   462  	DWAttr *a, *b;
   463  
   464  	if (die->attr->atr == attr)
   465  		return die->attr;
   466  
   467  	a = die->attr;
   468  	b = a->link;
   469  	while (b != nil) {
   470  		if (b->atr == attr) {
   471  			a->link = b->link;
   472  			b->link = die->attr;
   473  			die->attr = b;
   474  			return b;
   475  		}
   476  		a = b;
   477  		b = b->link;
   478  	}
   479  	return nil;
   480  }
   481  
   482  // Every DIE has at least a DW_AT_name attribute (but it will only be
   483  // written out if it is listed in the abbrev).	If its parent is
   484  // keeping an index, the new DIE will be inserted there.
   485  static DWDie*
   486  newdie(DWDie *parent, int abbrev, char *name)
   487  {
   488  	DWDie *die;
   489  	int h;
   490  
   491  	die = mal(sizeof *die);
   492  	die->abbrev = abbrev;
   493  	die->link = parent->child;
   494  	parent->child = die;
   495  
   496  	newattr(die, DW_AT_name, DW_CLS_STRING, strlen(name), name);
   497  
   498  	if (parent->hash) {
   499  		h = hashstr(name);
   500  		die->hlink = parent->hash[h];
   501  		parent->hash[h] = die;
   502  	}
   503  
   504  	return die;
   505  }
   506  
   507  static void
   508  mkindex(DWDie *die)
   509  {
   510  	die->hash = mal(HASHSIZE * sizeof(DWDie*));
   511  }
   512  
   513  static DWDie*
   514  walktypedef(DWDie *die)
   515  {
   516  	DWAttr *attr;
   517  
   518  	// Resolve typedef if present.
   519  	if (die->abbrev == DW_ABRV_TYPEDECL) {
   520  		for (attr = die->attr; attr; attr = attr->link) {
   521  			if (attr->atr == DW_AT_type && attr->cls == DW_CLS_REFERENCE && attr->data != nil) {
   522  				return (DWDie*)attr->data;
   523  			}
   524  		}
   525  	}
   526  	return die;
   527  }
   528  
   529  // Find child by AT_name using hashtable if available or linear scan
   530  // if not.
   531  static DWDie*
   532  find(DWDie *die, char* name)
   533  {
   534  	DWDie *a, *b, *die2;
   535  	int h;
   536  
   537  top:
   538  	if (die->hash == nil) {
   539  		for (a = die->child; a != nil; a = a->link)
   540  			if (strcmp(name, getattr(a, DW_AT_name)->data) == 0)
   541  				return a;
   542  		goto notfound;
   543  	}
   544  
   545  	h = hashstr(name);
   546  	a = die->hash[h];
   547  
   548  	if (a == nil)
   549  		goto notfound;
   550  
   551  
   552  	if (strcmp(name, getattr(a, DW_AT_name)->data) == 0)
   553  		return a;
   554  
   555  	// Move found ones to head of the list.
   556  	b = a->hlink;
   557  	while (b != nil) {
   558  		if (strcmp(name, getattr(b, DW_AT_name)->data) == 0) {
   559  			a->hlink = b->hlink;
   560  			b->hlink = die->hash[h];
   561  			die->hash[h] = b;
   562  			return b;
   563  		}
   564  		a = b;
   565  		b = b->hlink;
   566  	}
   567  
   568  notfound:
   569  	die2 = walktypedef(die);
   570  	if(die2 != die) {
   571  		die = die2;
   572  		goto top;
   573  	}
   574  
   575  	return nil;
   576  }
   577  
   578  static DWDie*
   579  find_or_diag(DWDie *die, char* name)
   580  {
   581  	DWDie *r;
   582  	r = find(die, name);
   583  	if (r == nil) {
   584  		diag("dwarf find: %s %p has no %s", getattr(die, DW_AT_name)->data, die, name);
   585  		errorexit();
   586  	}
   587  	return r;
   588  }
   589  
   590  static void
   591  adddwarfrel(Sym* sec, Sym* sym, vlong offsetbase, int siz, vlong addend)
   592  {
   593  	Reloc *r;
   594  
   595  	r = addrel(sec);
   596  	r->sym = sym;
   597  	r->xsym = sym;
   598  	r->off = cpos() - offsetbase;
   599  	r->siz = siz;
   600  	r->type = D_ADDR;
   601  	r->add = addend;
   602  	r->xadd = addend;
   603  	if(iself && thechar == '6')
   604  		addend = 0;
   605  	switch(siz) {
   606  	case 4:
   607  		LPUT(addend);
   608  		break;
   609  	case 8:
   610  		VPUT(addend);
   611  		break;
   612  	default:
   613  		diag("bad size in adddwarfrel");
   614  		break;
   615  	}
   616  }
   617  
   618  static DWAttr*
   619  newrefattr(DWDie *die, uint8 attr, DWDie* ref)
   620  {
   621  	if (ref == nil)
   622  		return nil;
   623  	return newattr(die, attr, DW_CLS_REFERENCE, 0, (char*)ref);
   624  }
   625  
   626  static int fwdcount;
   627  
   628  static void
   629  putattr(int abbrev, int form, int cls, vlong value, char *data)
   630  {
   631  	vlong off;
   632  
   633  	switch(form) {
   634  	case DW_FORM_addr:	// address
   635  		if(linkmode == LinkExternal) {
   636  			value -= ((Sym*)data)->value;
   637  			adddwarfrel(infosec, (Sym*)data, infoo, PtrSize, value);
   638  			break;
   639  		}
   640  		addrput(value);
   641  		break;
   642  
   643  	case DW_FORM_block1:	// block
   644  		if(cls == DW_CLS_ADDRESS) {
   645  			cput(1+PtrSize);
   646  			cput(DW_OP_addr);
   647  			if(linkmode == LinkExternal) {
   648  				value -= ((Sym*)data)->value;
   649  				adddwarfrel(infosec, (Sym*)data, infoo, PtrSize, value);
   650  				break;
   651  			}
   652  			addrput(value);
   653  			break;
   654  		}
   655  		value &= 0xff;
   656  		cput(value);
   657  		while(value--)
   658  			cput(*data++);
   659  		break;
   660  
   661  	case DW_FORM_block2:	// block
   662  		value &= 0xffff;
   663  		WPUT(value);
   664  		while(value--)
   665  			cput(*data++);
   666  		break;
   667  
   668  	case DW_FORM_block4:	// block
   669  		value &= 0xffffffff;
   670  		LPUT(value);
   671  		while(value--)
   672  			cput(*data++);
   673  		break;
   674  
   675  	case DW_FORM_block:	// block
   676  		uleb128put(value);
   677  		while(value--)
   678  			cput(*data++);
   679  		break;
   680  
   681  	case DW_FORM_data1:	// constant
   682  		cput(value);
   683  		break;
   684  
   685  	case DW_FORM_data2:	// constant
   686  		WPUT(value);
   687  		break;
   688  
   689  	case DW_FORM_data4:	// constant, {line,loclist,mac,rangelist}ptr
   690  		if(linkmode == LinkExternal && cls == DW_CLS_PTR) {
   691  			adddwarfrel(infosec, linesym, infoo, 4, value);
   692  			break;
   693  		}
   694  		LPUT(value);
   695  		break;
   696  
   697  	case DW_FORM_data8:	// constant, {line,loclist,mac,rangelist}ptr
   698  		VPUT(value);
   699  		break;
   700  
   701  	case DW_FORM_sdata:	// constant
   702  		sleb128put(value);
   703  		break;
   704  
   705  	case DW_FORM_udata:	// constant
   706  		uleb128put(value);
   707  		break;
   708  
   709  	case DW_FORM_string:	// string
   710  		strnput(data, value+1);
   711  		break;
   712  
   713  	case DW_FORM_flag:	// flag
   714  		cput(value?1:0);
   715  		break;
   716  
   717  	case DW_FORM_ref_addr:	// reference to a DIE in the .info section
   718  		// In DWARF 2 (which is what we claim to generate),
   719  		// the ref_addr is the same size as a normal address.
   720  		// In DWARF 3 it is always 32 bits, unless emitting a large
   721  		// (> 4 GB of debug info aka "64-bit") unit, which we don't implement.
   722  		if (data == nil) {
   723  			diag("dwarf: null reference in %d", abbrev);
   724  			if(PtrSize == 8)
   725  				VPUT(0); // invalid dwarf, gdb will complain.
   726  			else
   727  				LPUT(0); // invalid dwarf, gdb will complain.
   728  		} else {
   729  			off = ((DWDie*)data)->offs;
   730  			if (off == 0)
   731  				fwdcount++;
   732  			if(linkmode == LinkExternal) {
   733  				adddwarfrel(infosec, infosym, infoo, PtrSize, off);
   734  				break;
   735  			}
   736  			addrput(off);
   737  		}
   738  		break;
   739  
   740  	case DW_FORM_ref1:	// reference within the compilation unit
   741  	case DW_FORM_ref2:	// reference
   742  	case DW_FORM_ref4:	// reference
   743  	case DW_FORM_ref8:	// reference
   744  	case DW_FORM_ref_udata:	// reference
   745  
   746  	case DW_FORM_strp:	// string
   747  	case DW_FORM_indirect:	// (see Section 7.5.3)
   748  	default:
   749  		diag("dwarf: unsupported attribute form %d / class %d", form, cls);
   750  		errorexit();
   751  	}
   752  }
   753  
   754  // Note that we can (and do) add arbitrary attributes to a DIE, but
   755  // only the ones actually listed in the Abbrev will be written out.
   756  static void
   757  putattrs(int abbrev, DWAttr* attr)
   758  {
   759  	DWAttr *attrs[DW_AT_recursive + 1];
   760  	DWAttrForm* af;
   761  
   762  	memset(attrs, 0, sizeof attrs);
   763  	for( ; attr; attr = attr->link)
   764  		if (attr->atr < nelem(attrs))
   765  			attrs[attr->atr] = attr;
   766  
   767  	for(af = abbrevs[abbrev].attr; af->attr; af++)
   768  		if (attrs[af->attr])
   769  			putattr(abbrev, af->form,
   770  				attrs[af->attr]->cls,
   771  				attrs[af->attr]->value,
   772  				attrs[af->attr]->data);
   773  		else
   774  			putattr(abbrev, af->form, 0, 0, nil);
   775  }
   776  
   777  static void putdie(DWDie* die);
   778  
   779  static void
   780  putdies(DWDie* die)
   781  {
   782  	for(; die; die = die->link)
   783  		putdie(die);
   784  }
   785  
   786  static void
   787  putdie(DWDie* die)
   788  {
   789  	die->offs = cpos() - infoo;
   790  	uleb128put(die->abbrev);
   791  	putattrs(die->abbrev, die->attr);
   792  	if (abbrevs[die->abbrev].children) {
   793  		putdies(die->child);
   794  		cput(0);
   795  	}
   796  }
   797  
   798  static void
   799  reverselist(DWDie** list)
   800  {
   801  	DWDie *curr, *prev;
   802  
   803  	curr = *list;
   804  	prev = nil;
   805  	while(curr != nil) {
   806  		DWDie* next = curr->link;
   807  		curr->link = prev;
   808  		prev = curr;
   809  		curr = next;
   810  	}
   811  	*list = prev;
   812  }
   813  
   814  static void
   815  reversetree(DWDie** list)
   816  {
   817  	 DWDie *die;
   818  
   819  	 reverselist(list);
   820  	 for (die = *list; die != nil; die = die->link)
   821  		 if (abbrevs[die->abbrev].children)
   822  			 reversetree(&die->child);
   823  }
   824  
   825  static void
   826  newmemberoffsetattr(DWDie *die, int32 offs)
   827  {
   828  	char block[10];
   829  	int i;
   830  
   831  	i = 0;
   832  	if (offs != 0) {
   833  		block[i++] = DW_OP_consts;
   834  		i += sleb128enc(offs, block+i);
   835  		block[i++] = DW_OP_plus;
   836  	}
   837  	newattr(die, DW_AT_data_member_location, DW_CLS_BLOCK, i, mal(i));
   838  	memmove(die->attr->data, block, i);
   839  }
   840  
   841  // GDB doesn't like DW_FORM_addr for DW_AT_location, so emit a
   842  // location expression that evals to a const.
   843  static void
   844  newabslocexprattr(DWDie *die, vlong addr, Sym *sym)
   845  {
   846  	newattr(die, DW_AT_location, DW_CLS_ADDRESS, addr, (char*)sym);
   847  }
   848  
   849  
   850  // Fake attributes for slices, maps and channel
   851  enum {
   852  	DW_AT_internal_elem_type = 250,	 // channels and slices
   853  	DW_AT_internal_key_type = 251,	 // maps
   854  	DW_AT_internal_val_type = 252,	 // maps
   855  	DW_AT_internal_location = 253,	 // params and locals
   856  };
   857  
   858  static DWDie* defptrto(DWDie *dwtype);	// below
   859  
   860  // Lookup predefined types
   861  static Sym*
   862  lookup_or_diag(char *n)
   863  {
   864  	Sym *s;
   865  
   866  	s = rlookup(n, 0);
   867  	if (s == nil || s->size == 0) {
   868  		diag("dwarf: missing type: %s", n);
   869  		errorexit();
   870  	}
   871  	return s;
   872  }
   873  
   874  static void
   875  dotypedef(DWDie *parent, char *name, DWDie *def)
   876  {
   877  	DWDie *die;
   878  
   879  	// Only emit typedefs for real names.
   880  	if(strncmp(name, "map[", 4) == 0)
   881  		return;
   882  	if(strncmp(name, "struct {", 8) == 0)
   883  		return;
   884  	if(strncmp(name, "chan ", 5) == 0)
   885  		return;
   886  	if(*name == '[' || *name == '*')
   887  		return;
   888  	if(def == nil)
   889  		diag("dwarf: bad def in dotypedef");
   890  
   891  	// The typedef entry must be created after the def,
   892  	// so that future lookups will find the typedef instead
   893  	// of the real definition. This hooks the typedef into any
   894  	// circular definition loops, so that gdb can understand them.
   895  	die = newdie(parent, DW_ABRV_TYPEDECL, name);
   896  	newrefattr(die, DW_AT_type, def);
   897  }
   898  
   899  // Define gotype, for composite ones recurse into constituents.
   900  static DWDie*
   901  defgotype(Sym *gotype)
   902  {
   903  	DWDie *die, *fld;
   904  	Sym *s;
   905  	char *name, *f;
   906  	uint8 kind;
   907  	vlong bytesize;
   908  	int i, nfields;
   909  
   910  	if (gotype == nil)
   911  		return find_or_diag(&dwtypes, "<unspecified>");
   912  
   913  	if (strncmp("type.", gotype->name, 5) != 0) {
   914  		diag("dwarf: type name doesn't start with \".type\": %s", gotype->name);
   915  		return find_or_diag(&dwtypes, "<unspecified>");
   916  	}
   917  	name = gotype->name + 5;  // could also decode from Type.string
   918  
   919  	die = find(&dwtypes, name);
   920  	if (die != nil)
   921  		return die;
   922  
   923  	if (0 && debug['v'] > 2)
   924  		print("new type: %Y\n", gotype);
   925  
   926  	kind = decodetype_kind(gotype);
   927  	bytesize = decodetype_size(gotype);
   928  
   929  	switch (kind) {
   930  	case KindBool:
   931  		die = newdie(&dwtypes, DW_ABRV_BASETYPE, name);
   932  		newattr(die, DW_AT_encoding,  DW_CLS_CONSTANT, DW_ATE_boolean, 0);
   933  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
   934  		break;
   935  
   936  	case KindInt:
   937  	case KindInt8:
   938  	case KindInt16:
   939  	case KindInt32:
   940  	case KindInt64:
   941  		die = newdie(&dwtypes, DW_ABRV_BASETYPE, name);
   942  		newattr(die, DW_AT_encoding,  DW_CLS_CONSTANT, DW_ATE_signed, 0);
   943  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
   944  		break;
   945  
   946  	case KindUint:
   947  	case KindUint8:
   948  	case KindUint16:
   949  	case KindUint32:
   950  	case KindUint64:
   951  	case KindUintptr:
   952  		die = newdie(&dwtypes, DW_ABRV_BASETYPE, name);
   953  		newattr(die, DW_AT_encoding,  DW_CLS_CONSTANT, DW_ATE_unsigned, 0);
   954  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
   955  		break;
   956  
   957  	case KindFloat32:
   958  	case KindFloat64:
   959  		die = newdie(&dwtypes, DW_ABRV_BASETYPE, name);
   960  		newattr(die, DW_AT_encoding,  DW_CLS_CONSTANT, DW_ATE_float, 0);
   961  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
   962  		break;
   963  
   964  	case KindComplex64:
   965  	case KindComplex128:
   966  		die = newdie(&dwtypes, DW_ABRV_BASETYPE, name);
   967  		newattr(die, DW_AT_encoding,  DW_CLS_CONSTANT, DW_ATE_complex_float, 0);
   968  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
   969  		break;
   970  
   971  	case KindArray:
   972  		die = newdie(&dwtypes, DW_ABRV_ARRAYTYPE, name);
   973  		dotypedef(&dwtypes, name, die);
   974  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
   975  		s = decodetype_arrayelem(gotype);
   976  		newrefattr(die, DW_AT_type, defgotype(s));
   977  		fld = newdie(die, DW_ABRV_ARRAYRANGE, "range");
   978  		newattr(fld, DW_AT_upper_bound, DW_CLS_CONSTANT, decodetype_arraylen(gotype), 0);
   979  		newrefattr(fld, DW_AT_type, find_or_diag(&dwtypes, "uintptr"));
   980  		break;
   981  
   982  	case KindChan:
   983  		die = newdie(&dwtypes, DW_ABRV_CHANTYPE, name);
   984  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
   985  		s = decodetype_chanelem(gotype);
   986  		newrefattr(die, DW_AT_internal_elem_type, defgotype(s));
   987  		break;
   988  
   989  	case KindFunc:
   990  		die = newdie(&dwtypes, DW_ABRV_FUNCTYPE, name);
   991  		dotypedef(&dwtypes, name, die);
   992  		newrefattr(die, DW_AT_type, find_or_diag(&dwtypes, "void"));
   993  		nfields = decodetype_funcincount(gotype);
   994  		for (i = 0; i < nfields; i++) {
   995  			s = decodetype_funcintype(gotype, i);
   996  			fld = newdie(die, DW_ABRV_FUNCTYPEPARAM, s->name+5);
   997  			newrefattr(fld, DW_AT_type, defgotype(s));
   998  		}
   999  		if (decodetype_funcdotdotdot(gotype))
  1000  			newdie(die, DW_ABRV_DOTDOTDOT, "...");
  1001  		nfields = decodetype_funcoutcount(gotype);
  1002  		for (i = 0; i < nfields; i++) {
  1003  			s = decodetype_funcouttype(gotype, i);
  1004  			fld = newdie(die, DW_ABRV_FUNCTYPEPARAM, s->name+5);
  1005  			newrefattr(fld, DW_AT_type, defptrto(defgotype(s)));
  1006  		}
  1007  		break;
  1008  
  1009  	case KindInterface:
  1010  		die = newdie(&dwtypes, DW_ABRV_IFACETYPE, name);
  1011  		dotypedef(&dwtypes, name, die);
  1012  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
  1013  		nfields = decodetype_ifacemethodcount(gotype);
  1014  		if (nfields == 0)
  1015  			s = lookup_or_diag("type.runtime.eface");
  1016  		else
  1017  			s = lookup_or_diag("type.runtime.iface");
  1018  		newrefattr(die, DW_AT_type, defgotype(s));
  1019  		break;
  1020  
  1021  	case KindMap:
  1022  		die = newdie(&dwtypes, DW_ABRV_MAPTYPE, name);
  1023  		s = decodetype_mapkey(gotype);
  1024  		newrefattr(die, DW_AT_internal_key_type, defgotype(s));
  1025  		s = decodetype_mapvalue(gotype);
  1026  		newrefattr(die, DW_AT_internal_val_type, defgotype(s));
  1027  		break;
  1028  
  1029  	case KindPtr:
  1030  		die = newdie(&dwtypes, DW_ABRV_PTRTYPE, name);
  1031  		dotypedef(&dwtypes, name, die);
  1032  		s = decodetype_ptrelem(gotype);
  1033  		newrefattr(die, DW_AT_type, defgotype(s));
  1034  		break;
  1035  
  1036  	case KindSlice:
  1037  		die = newdie(&dwtypes, DW_ABRV_SLICETYPE, name);
  1038  		dotypedef(&dwtypes, name, die);
  1039  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
  1040  		s = decodetype_arrayelem(gotype);
  1041  		newrefattr(die, DW_AT_internal_elem_type, defgotype(s));
  1042  		break;
  1043  
  1044  	case KindString:
  1045  		die = newdie(&dwtypes, DW_ABRV_STRINGTYPE, name);
  1046  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
  1047  		break;
  1048  
  1049  	case KindStruct:
  1050  		die = newdie(&dwtypes, DW_ABRV_STRUCTTYPE, name);
  1051  		dotypedef(&dwtypes, name, die);
  1052  		newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, bytesize, 0);
  1053  		nfields = decodetype_structfieldcount(gotype);
  1054  		for (i = 0; i < nfields; i++) {
  1055  			f = decodetype_structfieldname(gotype, i);
  1056  			s = decodetype_structfieldtype(gotype, i);
  1057  			if (f == nil)
  1058  				f = s->name + 5;	 // skip "type."
  1059  			fld = newdie(die, DW_ABRV_STRUCTFIELD, f);
  1060  			newrefattr(fld, DW_AT_type, defgotype(s));
  1061  			newmemberoffsetattr(fld, decodetype_structfieldoffs(gotype, i));
  1062  		}
  1063  		break;
  1064  
  1065  	case KindUnsafePointer:
  1066  		die = newdie(&dwtypes, DW_ABRV_BARE_PTRTYPE, name);
  1067  		break;
  1068  
  1069  	default:
  1070  		diag("dwarf: definition of unknown kind %d: %s", kind, gotype->name);
  1071  		die = newdie(&dwtypes, DW_ABRV_TYPEDECL, name);
  1072  		newrefattr(die, DW_AT_type, find_or_diag(&dwtypes, "<unspecified>"));
  1073  	 }
  1074  
  1075  	return die;
  1076  }
  1077  
  1078  // Find or construct *T given T.
  1079  static DWDie*
  1080  defptrto(DWDie *dwtype)
  1081  {
  1082  	char ptrname[1024];
  1083  	DWDie *die;
  1084  
  1085  	snprint(ptrname, sizeof ptrname, "*%s", getattr(dwtype, DW_AT_name)->data);
  1086  	die = find(&dwtypes, ptrname);
  1087  	if (die == nil) {
  1088  		die = newdie(&dwtypes, DW_ABRV_PTRTYPE,
  1089  			     strcpy(mal(strlen(ptrname)+1), ptrname));
  1090  		newrefattr(die, DW_AT_type, dwtype);
  1091  	}
  1092  	return die;
  1093  }
  1094  
  1095  // Copies src's children into dst. Copies attributes by value.
  1096  // DWAttr.data is copied as pointer only.
  1097  static void
  1098  copychildren(DWDie *dst, DWDie *src)
  1099  {
  1100  	DWDie *c;
  1101  	DWAttr *a;
  1102  
  1103  	for (src = src->child; src != nil; src = src->link) {
  1104  		c = newdie(dst, src->abbrev, getattr(src, DW_AT_name)->data);
  1105  		for (a = src->attr; a != nil; a = a->link)
  1106  			newattr(c, a->atr, a->cls, a->value, a->data);
  1107  		copychildren(c, src);
  1108  	}
  1109  	reverselist(&dst->child);
  1110  }
  1111  
  1112  // Search children (assumed to have DW_TAG_member) for the one named
  1113  // field and set its DW_AT_type to dwtype
  1114  static void
  1115  substitutetype(DWDie *structdie, char *field, DWDie* dwtype)
  1116  {
  1117  	DWDie *child;
  1118  	DWAttr *a;
  1119  
  1120  	child = find_or_diag(structdie, field);
  1121  	if (child == nil)
  1122  		return;
  1123  
  1124  	a = getattr(child, DW_AT_type);
  1125  	if (a != nil)
  1126  		a->data = (char*) dwtype;
  1127  	else
  1128  		newrefattr(child, DW_AT_type, dwtype);
  1129  }
  1130  
  1131  static void
  1132  synthesizestringtypes(DWDie* die)
  1133  {
  1134  	DWDie *prototype;
  1135  
  1136  	prototype = walktypedef(defgotype(lookup_or_diag("type.runtime._string")));
  1137  	if (prototype == nil)
  1138  		return;
  1139  
  1140  	for (; die != nil; die = die->link) {
  1141  		if (die->abbrev != DW_ABRV_STRINGTYPE)
  1142  			continue;
  1143  		copychildren(die, prototype);
  1144  	}
  1145  }
  1146  
  1147  static void
  1148  synthesizeslicetypes(DWDie *die)
  1149  {
  1150  	DWDie *prototype, *elem;
  1151  
  1152  	prototype = walktypedef(defgotype(lookup_or_diag("type.runtime.slice")));
  1153  	if (prototype == nil)
  1154  		return;
  1155  
  1156  	for (; die != nil; die = die->link) {
  1157  		if (die->abbrev != DW_ABRV_SLICETYPE)
  1158  			continue;
  1159  		copychildren(die, prototype);
  1160  		elem = (DWDie*) getattr(die, DW_AT_internal_elem_type)->data;
  1161  		substitutetype(die, "array", defptrto(elem));
  1162  	}
  1163  }
  1164  
  1165  static char*
  1166  mkinternaltypename(char *base, char *arg1, char *arg2)
  1167  {
  1168  	char buf[1024];
  1169  	char *n;
  1170  
  1171  	if (arg2 == nil)
  1172  		snprint(buf, sizeof buf, "%s<%s>", base, arg1);
  1173  	else
  1174  		snprint(buf, sizeof buf, "%s<%s,%s>", base, arg1, arg2);
  1175  	n = mal(strlen(buf) + 1);
  1176  	memmove(n, buf, strlen(buf));
  1177  	return n;
  1178  }
  1179  
  1180  // synthesizemaptypes is way too closely married to runtime/hashmap.c
  1181  enum {
  1182  	MaxKeySize = 128,
  1183  	MaxValSize = 128,
  1184  	BucketSize = 8,
  1185  };
  1186  
  1187  static void
  1188  synthesizemaptypes(DWDie *die)
  1189  {
  1190  
  1191  	DWDie *hash, *bucket, *dwh, *dwhk, *dwhv, *dwhb, *keytype, *valtype, *fld;
  1192  	int indirect_key, indirect_val;
  1193  	int keysize, valsize;
  1194  	DWAttr *a;
  1195  
  1196  	hash		= walktypedef(defgotype(lookup_or_diag("type.runtime.hmap")));
  1197  	bucket		= walktypedef(defgotype(lookup_or_diag("type.runtime.bucket")));
  1198  
  1199  	if (hash == nil)
  1200  		return;
  1201  
  1202  	for (; die != nil; die = die->link) {
  1203  		if (die->abbrev != DW_ABRV_MAPTYPE)
  1204  			continue;
  1205  
  1206  		keytype = walktypedef((DWDie*) getattr(die, DW_AT_internal_key_type)->data);
  1207  		valtype = walktypedef((DWDie*) getattr(die, DW_AT_internal_val_type)->data);
  1208  
  1209  		// compute size info like hashmap.c does.
  1210  		a = getattr(keytype, DW_AT_byte_size);
  1211  		keysize = a ? a->value : PtrSize;  // We don't store size with Pointers
  1212  		a = getattr(valtype, DW_AT_byte_size);
  1213  		valsize = a ? a->value : PtrSize;
  1214  		indirect_key = 0;
  1215  		indirect_val = 0;
  1216  		if(keysize > MaxKeySize) {
  1217  			keysize = PtrSize;
  1218  			indirect_key = 1;
  1219  		}
  1220  		if(valsize > MaxValSize) {
  1221  			valsize = PtrSize;
  1222  			indirect_val = 1;
  1223  		}
  1224  
  1225  		// Construct type to represent an array of BucketSize keys
  1226  		dwhk = newdie(&dwtypes, DW_ABRV_ARRAYTYPE,
  1227  			      mkinternaltypename("[]key",
  1228  						 getattr(keytype, DW_AT_name)->data, nil));
  1229  		newattr(dwhk, DW_AT_byte_size, DW_CLS_CONSTANT, BucketSize * keysize, 0);
  1230  		newrefattr(dwhk, DW_AT_type, indirect_key ? defptrto(keytype) : keytype);
  1231  		fld = newdie(dwhk, DW_ABRV_ARRAYRANGE, "size");
  1232  		newattr(fld, DW_AT_upper_bound, DW_CLS_CONSTANT, BucketSize, 0);
  1233  		newrefattr(fld, DW_AT_type, find_or_diag(&dwtypes, "uintptr"));
  1234  		
  1235  		// Construct type to represent an array of BucketSize values
  1236  		dwhv = newdie(&dwtypes, DW_ABRV_ARRAYTYPE, 
  1237  			      mkinternaltypename("[]val",
  1238  						 getattr(valtype, DW_AT_name)->data, nil));
  1239  		newattr(dwhv, DW_AT_byte_size, DW_CLS_CONSTANT, BucketSize * valsize, 0);
  1240  		newrefattr(dwhv, DW_AT_type, indirect_val ? defptrto(valtype) : valtype);
  1241  		fld = newdie(dwhv, DW_ABRV_ARRAYRANGE, "size");
  1242  		newattr(fld, DW_AT_upper_bound, DW_CLS_CONSTANT, BucketSize, 0);
  1243  		newrefattr(fld, DW_AT_type, find_or_diag(&dwtypes, "uintptr"));
  1244  
  1245  		// Construct bucket<K,V>
  1246  		dwhb = newdie(&dwtypes, DW_ABRV_STRUCTTYPE,
  1247  			      mkinternaltypename("bucket",
  1248  						 getattr(keytype, DW_AT_name)->data,
  1249  						 getattr(valtype, DW_AT_name)->data));
  1250  		copychildren(dwhb, bucket);
  1251  		fld = newdie(dwhb, DW_ABRV_STRUCTFIELD, "keys");
  1252  		newrefattr(fld, DW_AT_type, dwhk);
  1253  		newmemberoffsetattr(fld, BucketSize + PtrSize);
  1254  		fld = newdie(dwhb, DW_ABRV_STRUCTFIELD, "values");
  1255  		newrefattr(fld, DW_AT_type, dwhv);
  1256  		newmemberoffsetattr(fld, BucketSize + PtrSize + BucketSize * keysize);
  1257  		newattr(dwhb, DW_AT_byte_size, DW_CLS_CONSTANT, BucketSize + PtrSize + BucketSize * keysize + BucketSize * valsize, 0);
  1258  		substitutetype(dwhb, "overflow", defptrto(dwhb));
  1259  
  1260  		// Construct hash<K,V>
  1261  		dwh = newdie(&dwtypes, DW_ABRV_STRUCTTYPE,
  1262  			mkinternaltypename("hash",
  1263  				getattr(keytype, DW_AT_name)->data,
  1264  				getattr(valtype, DW_AT_name)->data));
  1265  		copychildren(dwh, hash);
  1266  		substitutetype(dwh, "buckets", defptrto(dwhb));
  1267  		substitutetype(dwh, "oldbuckets", defptrto(dwhb));
  1268  		newattr(dwh, DW_AT_byte_size, DW_CLS_CONSTANT,
  1269  			getattr(hash, DW_AT_byte_size)->value, nil);
  1270  
  1271  		// make map type a pointer to hash<K,V>
  1272  		newrefattr(die, DW_AT_type, defptrto(dwh));
  1273  	}
  1274  }
  1275  
  1276  static void
  1277  synthesizechantypes(DWDie *die)
  1278  {
  1279  	DWDie *sudog, *waitq, *hchan,
  1280  		*dws, *dww, *dwh, *elemtype;
  1281  	DWAttr *a;
  1282  	int elemsize, sudogsize;
  1283  
  1284  	sudog = walktypedef(defgotype(lookup_or_diag("type.runtime.sudog")));
  1285  	waitq = walktypedef(defgotype(lookup_or_diag("type.runtime.waitq")));
  1286  	hchan = walktypedef(defgotype(lookup_or_diag("type.runtime.hchan")));
  1287  	if (sudog == nil || waitq == nil || hchan == nil)
  1288  		return;
  1289  
  1290  	sudogsize = getattr(sudog, DW_AT_byte_size)->value;
  1291  
  1292  	for (; die != nil; die = die->link) {
  1293  		if (die->abbrev != DW_ABRV_CHANTYPE)
  1294  			continue;
  1295  		elemtype = (DWDie*) getattr(die, DW_AT_internal_elem_type)->data;
  1296  		a = getattr(elemtype, DW_AT_byte_size);
  1297  		elemsize = a ? a->value : PtrSize;
  1298  
  1299  		// sudog<T>
  1300  		dws = newdie(&dwtypes, DW_ABRV_STRUCTTYPE,
  1301  			mkinternaltypename("sudog",
  1302  				getattr(elemtype, DW_AT_name)->data, nil));
  1303  		copychildren(dws, sudog);
  1304  		substitutetype(dws, "elem", elemtype);
  1305  		newattr(dws, DW_AT_byte_size, DW_CLS_CONSTANT,
  1306  			sudogsize + (elemsize > 8 ? elemsize - 8 : 0), nil);
  1307  
  1308  		// waitq<T>
  1309  		dww = newdie(&dwtypes, DW_ABRV_STRUCTTYPE,
  1310  			mkinternaltypename("waitq", getattr(elemtype, DW_AT_name)->data, nil));
  1311  		copychildren(dww, waitq);
  1312  		substitutetype(dww, "first", defptrto(dws));
  1313  		substitutetype(dww, "last",  defptrto(dws));
  1314  		newattr(dww, DW_AT_byte_size, DW_CLS_CONSTANT,
  1315  			getattr(waitq, DW_AT_byte_size)->value, nil);
  1316  
  1317  		// hchan<T>
  1318  		dwh = newdie(&dwtypes, DW_ABRV_STRUCTTYPE,
  1319  			mkinternaltypename("hchan", getattr(elemtype, DW_AT_name)->data, nil));
  1320  		copychildren(dwh, hchan);
  1321  		substitutetype(dwh, "recvq", dww);
  1322  		substitutetype(dwh, "sendq", dww);
  1323  		newattr(dwh, DW_AT_byte_size, DW_CLS_CONSTANT,
  1324  			getattr(hchan, DW_AT_byte_size)->value, nil);
  1325  
  1326  		newrefattr(die, DW_AT_type, defptrto(dwh));
  1327  	}
  1328  }
  1329  
  1330  // For use with pass.c::genasmsym
  1331  static void
  1332  defdwsymb(Sym* sym, char *s, int t, vlong v, vlong size, int ver, Sym *gotype)
  1333  {
  1334  	DWDie *dv, *dt;
  1335  
  1336  	USED(size);
  1337  	if (strncmp(s, "go.string.", 10) == 0)
  1338  		return;
  1339  
  1340  	if (strncmp(s, "type.", 5) == 0 && strcmp(s, "type.*") != 0 && strncmp(s, "type..", 6) != 0) {
  1341  		defgotype(sym);
  1342  		return;
  1343  	}
  1344  
  1345  	dv = nil;
  1346  
  1347  	switch (t) {
  1348  	default:
  1349  		return;
  1350  	case 'd':
  1351  	case 'b':
  1352  	case 'D':
  1353  	case 'B':
  1354  		dv = newdie(&dwglobals, DW_ABRV_VARIABLE, s);
  1355  		newabslocexprattr(dv, v, sym);
  1356  		if (ver == 0)
  1357  			newattr(dv, DW_AT_external, DW_CLS_FLAG, 1, 0);
  1358  		// fallthrough
  1359  	case 'a':
  1360  	case 'p':
  1361  		dt = defgotype(gotype);
  1362  	}
  1363  
  1364  	if (dv != nil)
  1365  		newrefattr(dv, DW_AT_type, dt);
  1366  }
  1367  
  1368  // TODO(lvd) For now, just append them all to the first compilation
  1369  // unit (that should be main), in the future distribute them to the
  1370  // appropriate compilation units.
  1371  static void
  1372  movetomodule(DWDie *parent)
  1373  {
  1374  	DWDie *die;
  1375  
  1376  	for (die = dwroot.child->child; die->link != nil; die = die->link) /* nix */;
  1377  	die->link = parent->child;
  1378  }
  1379  
  1380  /*
  1381   * Filename fragments for the line history stack.
  1382   */
  1383  
  1384  static char **ftab;
  1385  static int ftabsize;
  1386  
  1387  void
  1388  dwarfaddfrag(int n, char *frag)
  1389  {
  1390  	int s;
  1391  
  1392  	if (n >= ftabsize) {
  1393  		s = ftabsize;
  1394  		ftabsize = 1 + n + (n >> 2);
  1395  		ftab = erealloc(ftab, ftabsize * sizeof(ftab[0]));
  1396  		memset(ftab + s, 0, (ftabsize - s) * sizeof(ftab[0]));
  1397  	}
  1398  
  1399  	if (*frag == '<')
  1400  		frag++;
  1401  	ftab[n] = frag;
  1402  }
  1403  
  1404  // Returns a malloc'ed string, piecewise copied from the ftab.
  1405  static char *
  1406  decodez(char *s)
  1407  {
  1408  	int len, o;
  1409  	char *ss, *f;
  1410  	char *r, *rb, *re;
  1411  
  1412  	len = 0;
  1413  	ss = s + 1;	// first is 0
  1414  	while((o = ((uint8)ss[0] << 8) | (uint8)ss[1]) != 0) {
  1415  		if (o < 0 || o >= ftabsize) {
  1416  			diag("dwarf: corrupt z entry");
  1417  			return 0;
  1418  		}
  1419  		f = ftab[o];
  1420  		if (f == nil) {
  1421  			diag("dwarf: corrupt z entry");
  1422  			return 0;
  1423  		}
  1424  		len += strlen(f) + 1;	// for the '/'
  1425  		ss += 2;
  1426  	}
  1427  
  1428  	if (len == 0)
  1429  		return 0;
  1430  
  1431  	r = malloc(len + 1);
  1432  	if(r == nil) {
  1433  		diag("out of memory");
  1434  		errorexit();
  1435  	}
  1436  	rb = r;
  1437  	re = rb + len + 1;
  1438  
  1439  	s++;
  1440  	while((o = ((uint8)s[0] << 8) | (uint8)s[1]) != 0) {
  1441  		f = ftab[o];
  1442  		if (rb == r || rb[-1] == '/')
  1443  			rb = seprint(rb, re, "%s", f);
  1444  		else
  1445  			rb = seprint(rb, re, "/%s", f);
  1446  		s += 2;
  1447  	}
  1448  	return r;
  1449  }
  1450  
  1451  /*
  1452   * The line history itself
  1453   */
  1454  
  1455  static char **histfile;	   // [0] holds "<eof>", DW_LNS_set_file arguments must be > 0.
  1456  static int  histfilesize;
  1457  static int  histfilecap;
  1458  
  1459  static void
  1460  clearhistfile(void)
  1461  {
  1462  	int i;
  1463  
  1464  	// [0] holds "<eof>"
  1465  	for (i = 1; i < histfilesize; i++)
  1466  		free(histfile[i]);
  1467  	histfilesize = 0;
  1468  }
  1469  
  1470  static int
  1471  addhistfile(char *zentry)
  1472  {
  1473  	char *fname;
  1474  
  1475  	if (histfilesize == histfilecap) {
  1476  		histfilecap = 2 * histfilecap + 2;
  1477  		histfile = erealloc(histfile, histfilecap * sizeof(char*));
  1478  	}
  1479  	if (histfilesize == 0)
  1480  		histfile[histfilesize++] = "<eof>";
  1481  
  1482  	fname = decodez(zentry);
  1483  //	print("addhistfile %d: %s\n", histfilesize, fname);
  1484  	if (fname == 0)
  1485  		return -1;
  1486  
  1487  	// Don't fill with duplicates (check only top one).
  1488  	if (strcmp(fname, histfile[histfilesize-1]) == 0) {
  1489  		free(fname);
  1490  		return histfilesize - 1;
  1491  	}
  1492  
  1493  	histfile[histfilesize++] = fname;
  1494  	return histfilesize - 1;
  1495  }
  1496  
  1497  // if the histfile stack contains ..../runtime/runtime_defs.go
  1498  // use that to set gdbscript
  1499  static void
  1500  finddebugruntimepath(void)
  1501  {
  1502  	int i, l;
  1503  	char *c;
  1504  
  1505  	for (i = 1; i < histfilesize; i++) {
  1506  		if ((c = strstr(histfile[i], "runtime/zruntime_defs")) != nil) {
  1507  			l = c - histfile[i];
  1508  			memmove(gdbscript, histfile[i], l);
  1509  			memmove(gdbscript + l, "runtime/runtime-gdb.py", strlen("runtime/runtime-gdb.py") + 1);
  1510  			break;
  1511  		}
  1512  	}
  1513  }
  1514  
  1515  // Go's runtime C sources are sane, and Go sources nest only 1 level,
  1516  // so a handful would be plenty, if it weren't for the fact that line
  1517  // directives can push an unlimited number of them.
  1518  static struct {
  1519  	int file;
  1520  	vlong line;
  1521  } *includestack;
  1522  static int includestacksize;
  1523  static int includetop;
  1524  static vlong absline;
  1525  
  1526  typedef struct Linehist Linehist;
  1527  struct Linehist {
  1528  	Linehist *link;
  1529  	vlong absline;
  1530  	vlong line;
  1531  	int file;
  1532  };
  1533  
  1534  static Linehist *linehist;
  1535  
  1536  static void
  1537  checknesting(void)
  1538  {
  1539  	if (includetop < 0) {
  1540  		diag("dwarf: corrupt z stack");
  1541  		errorexit();
  1542  	}
  1543  	if (includetop >= includestacksize) {
  1544  		includestacksize += 1;
  1545  		includestacksize <<= 2;
  1546  //		print("checknesting: growing to %d\n", includestacksize);
  1547  		includestack = erealloc(includestack, includestacksize * sizeof *includestack);	       
  1548  	}
  1549  }
  1550  
  1551  /*
  1552   * Return false if the a->link chain contains no history, otherwise
  1553   * returns true and finds z and Z entries in the Auto list (of a
  1554   * Prog), and resets the history stack
  1555   */
  1556  static int
  1557  inithist(Auto *a)
  1558  {
  1559  	Linehist *lh;
  1560  
  1561  	for (; a; a = a->link)
  1562  		if (a->type == D_FILE)
  1563  			break;
  1564  	if (a==nil)
  1565  		return 0;
  1566  
  1567  	// We have a new history.  They are guaranteed to come completely
  1568  	// at the beginning of the compilation unit.
  1569  	if (a->aoffset != 1) {
  1570  		diag("dwarf: stray 'z' with offset %d", a->aoffset);
  1571  		return 0;
  1572  	}
  1573  
  1574  	// Clear the history.
  1575  	clearhistfile();
  1576  	includetop = 0;
  1577  	checknesting();
  1578  	includestack[includetop].file = 0;
  1579  	includestack[includetop].line = -1;
  1580  	absline = 0;
  1581  	while (linehist != nil) {
  1582  		lh = linehist->link;
  1583  		free(linehist);
  1584  		linehist = lh;
  1585  	}
  1586  
  1587  	// Construct the new one.
  1588  	for (; a; a = a->link) {
  1589  		if (a->type == D_FILE) {  // 'z'
  1590  			int f = addhistfile(a->asym->name);
  1591  			if (f < 0) {	// pop file
  1592  				includetop--;
  1593  				checknesting();
  1594  			} else {	// pushed a file (potentially same)
  1595  				includestack[includetop].line += a->aoffset - absline;
  1596  				includetop++;
  1597  				checknesting();
  1598  				includestack[includetop].file = f;
  1599  				includestack[includetop].line = 1;
  1600  			}
  1601  			absline = a->aoffset;
  1602  		} else if (a->type == D_FILE1) {  // 'Z'
  1603  			// We could just fixup the current
  1604  			// linehist->line, but there doesn't appear to
  1605  			// be a guarantee that every 'Z' is preceded
  1606  			// by its own 'z', so do the safe thing and
  1607  			// update the stack and push a new Linehist
  1608  			// entry
  1609  			includestack[includetop].line =	 a->aoffset;
  1610  		} else
  1611  			continue;
  1612  		if (linehist == 0 || linehist->absline != absline) {
  1613  			Linehist* lh = malloc(sizeof *lh);
  1614  			if(lh == nil) {
  1615  				diag("out of memory");
  1616  				errorexit();
  1617  			}
  1618  			lh->link = linehist;
  1619  			lh->absline = absline;
  1620  			linehist = lh;
  1621  		}
  1622  		linehist->file = includestack[includetop].file;
  1623  		linehist->line = includestack[includetop].line;
  1624  	}
  1625  	return 1;
  1626  }
  1627  
  1628  static Linehist *
  1629  searchhist(vlong absline)
  1630  {
  1631  	Linehist *lh;
  1632  
  1633  	for (lh = linehist; lh; lh = lh->link)
  1634  		if (lh->absline <= absline)
  1635  			break;
  1636  	return lh;
  1637  }
  1638  
  1639  static int
  1640  guesslang(char *s)
  1641  {
  1642  	if(strlen(s) >= 3 && strcmp(s+strlen(s)-3, ".go") == 0)
  1643  		return DW_LANG_Go;
  1644  
  1645  	return DW_LANG_C;
  1646  }
  1647  
  1648  /*
  1649   * Generate short opcodes when possible, long ones when neccesary.
  1650   * See section 6.2.5
  1651   */
  1652  
  1653  enum {
  1654  	LINE_BASE = -1,
  1655  	LINE_RANGE = 4,
  1656  	OPCODE_BASE = 5
  1657  };
  1658  
  1659  static void
  1660  putpclcdelta(vlong delta_pc, vlong delta_lc)
  1661  {
  1662  	if (LINE_BASE <= delta_lc && delta_lc < LINE_BASE+LINE_RANGE) {
  1663  		vlong opcode = OPCODE_BASE + (delta_lc - LINE_BASE) + (LINE_RANGE * delta_pc);
  1664  		if (OPCODE_BASE <= opcode && opcode < 256) {
  1665  			cput(opcode);
  1666  			return;
  1667  		}
  1668  	}
  1669  
  1670  	if (delta_pc) {
  1671  		cput(DW_LNS_advance_pc);
  1672  		sleb128put(delta_pc);
  1673  	}
  1674  
  1675  	cput(DW_LNS_advance_line);
  1676  	sleb128put(delta_lc);
  1677  	cput(DW_LNS_copy);
  1678  }
  1679  
  1680  static void
  1681  newcfaoffsetattr(DWDie *die, int32 offs)
  1682  {
  1683  	char block[10];
  1684  	int i;
  1685  
  1686  	i = 0;
  1687  
  1688  	block[i++] = DW_OP_call_frame_cfa;
  1689  	if (offs != 0) {
  1690  		block[i++] = DW_OP_consts;
  1691  		i += sleb128enc(offs, block+i);
  1692  		block[i++] = DW_OP_plus;
  1693  	}
  1694  	newattr(die, DW_AT_location, DW_CLS_BLOCK, i, mal(i));
  1695  	memmove(die->attr->data, block, i);
  1696  }
  1697  
  1698  static char*
  1699  mkvarname(char* name, int da)
  1700  {
  1701  	char buf[1024];
  1702  	char *n;
  1703  
  1704  	snprint(buf, sizeof buf, "%s#%d", name, da);
  1705  	n = mal(strlen(buf) + 1);
  1706  	memmove(n, buf, strlen(buf));
  1707  	return n;
  1708  }
  1709  
  1710  /*
  1711   * Walk prog table, emit line program and build DIE tree.
  1712   */
  1713  
  1714  // flush previous compilation unit.
  1715  static void
  1716  flushunit(DWDie *dwinfo, vlong pc, Sym *pcsym, vlong unitstart, int32 header_length)
  1717  {
  1718  	vlong here;
  1719  
  1720  	if (dwinfo != nil && pc != 0) {
  1721  		newattr(dwinfo, DW_AT_high_pc, DW_CLS_ADDRESS, pc+1, (char*)pcsym);
  1722  	}
  1723  
  1724  	if (unitstart >= 0) {
  1725  		cput(0);  // start extended opcode
  1726  		uleb128put(1);
  1727  		cput(DW_LNE_end_sequence);
  1728  
  1729  		here = cpos();
  1730  		cseek(unitstart);
  1731  		LPUT(here - unitstart - sizeof(int32));	 // unit_length
  1732  		WPUT(2);  // dwarf version
  1733  		LPUT(header_length); // header length starting here
  1734  		cseek(here);
  1735  	}
  1736  }
  1737  
  1738  static void
  1739  writelines(void)
  1740  {
  1741  	Prog *q;
  1742  	Sym *s, *epcs;
  1743  	Auto *a;
  1744  	vlong unitstart, headerend, offs;
  1745  	vlong pc, epc, lc, llc, lline;
  1746  	int currfile;
  1747  	int i, lang, da, dt;
  1748  	Linehist *lh;
  1749  	DWDie *dwinfo, *dwfunc, *dwvar, **dws;
  1750  	DWDie *varhash[HASHSIZE];
  1751  	char *n, *nn;
  1752  
  1753  	if(linesec == S)
  1754  		linesec = lookup(".dwarfline", 0);
  1755  	linesec->nr = 0;
  1756  
  1757  	unitstart = -1;
  1758  	headerend = -1;
  1759  	pc = 0;
  1760  	epc = 0;
  1761  	epcs = S;
  1762  	lc = 1;
  1763  	llc = 1;
  1764  	currfile = -1;
  1765  	lineo = cpos();
  1766  	dwinfo = nil;
  1767  
  1768  	for(cursym = textp; cursym != nil; cursym = cursym->next) {
  1769  		s = cursym;
  1770  		if(s->text == P)
  1771  			continue;
  1772  
  1773  		// Look for history stack.  If we find one,
  1774  		// we're entering a new compilation unit
  1775  
  1776  		if (inithist(s->autom)) {
  1777  			flushunit(dwinfo, epc, epcs, unitstart, headerend - unitstart - 10);
  1778  			unitstart = cpos();
  1779  
  1780  			if(debug['v'] > 1) {
  1781  				print("dwarf writelines found %s\n", histfile[1]);
  1782  				Linehist* lh;
  1783  				for (lh = linehist; lh; lh = lh->link)
  1784  					print("\t%8lld: [%4lld]%s\n",
  1785  					      lh->absline, lh->line, histfile[lh->file]);
  1786  			}
  1787  
  1788  			lang = guesslang(histfile[1]);
  1789  			finddebugruntimepath();
  1790  
  1791  			dwinfo = newdie(&dwroot, DW_ABRV_COMPUNIT, estrdup(histfile[1]));
  1792  			newattr(dwinfo, DW_AT_language, DW_CLS_CONSTANT,lang, 0);
  1793  			newattr(dwinfo, DW_AT_stmt_list, DW_CLS_PTR, unitstart - lineo, 0);
  1794  			newattr(dwinfo, DW_AT_low_pc, DW_CLS_ADDRESS, s->text->pc, (char*)s);
  1795  
  1796  			// Write .debug_line Line Number Program Header (sec 6.2.4)
  1797  			// Fields marked with (*) must be changed for 64-bit dwarf
  1798  			LPUT(0);   // unit_length (*), will be filled in by flushunit.
  1799  			WPUT(2);   // dwarf version (appendix F)
  1800  			LPUT(0);   // header_length (*), filled in by flushunit.
  1801  			// cpos == unitstart + 4 + 2 + 4
  1802  			cput(1);   // minimum_instruction_length
  1803  			cput(1);   // default_is_stmt
  1804  			cput(LINE_BASE);     // line_base
  1805  			cput(LINE_RANGE);    // line_range
  1806  			cput(OPCODE_BASE);   // opcode_base (we only use 1..4)
  1807  			cput(0);   // standard_opcode_lengths[1]
  1808  			cput(1);   // standard_opcode_lengths[2]
  1809  			cput(1);   // standard_opcode_lengths[3]
  1810  			cput(1);   // standard_opcode_lengths[4]
  1811  			cput(0);   // include_directories  (empty)
  1812  
  1813  			for (i=1; i < histfilesize; i++) {
  1814  				strnput(histfile[i], strlen(histfile[i]) + 4);
  1815  				// 4 zeros: the string termination + 3 fields.
  1816  			}
  1817  
  1818  			cput(0);   // terminate file_names.
  1819  			headerend = cpos();
  1820  
  1821  			pc = s->text->pc;
  1822  			epc = pc;
  1823  			epcs = s;
  1824  			currfile = 1;
  1825  			lc = 1;
  1826  			llc = 1;
  1827  
  1828  			cput(0);  // start extended opcode
  1829  			uleb128put(1 + PtrSize);
  1830  			cput(DW_LNE_set_address);
  1831  
  1832  			if(linkmode == LinkExternal)
  1833  				adddwarfrel(linesec, s, lineo, PtrSize, 0);
  1834  			else
  1835  				addrput(pc);
  1836  		}
  1837  		if(s->text == nil)
  1838  			continue;
  1839  
  1840  		if (unitstart < 0) {
  1841  			diag("dwarf: reachable code before seeing any history: %P", s->text);
  1842  			continue;
  1843  		}
  1844  
  1845  		dwfunc = newdie(dwinfo, DW_ABRV_FUNCTION, s->name);
  1846  		newattr(dwfunc, DW_AT_low_pc, DW_CLS_ADDRESS, s->value, (char*)s);
  1847  		epc = s->value + s->size;
  1848  		newattr(dwfunc, DW_AT_high_pc, DW_CLS_ADDRESS, epc, (char*)s);
  1849  		if (s->version == 0)
  1850  			newattr(dwfunc, DW_AT_external, DW_CLS_FLAG, 1, 0);
  1851  
  1852  		if(s->text->link == nil)
  1853  			continue;
  1854  
  1855  		for(q = s->text; q != P; q = q->link) {
  1856  			lh = searchhist(q->line);
  1857  			if (lh == nil) {
  1858  				diag("dwarf: corrupt history or bad absolute line: %P", q);
  1859  				continue;
  1860  			}
  1861  
  1862  			if (lh->file < 1) {  // 0 is the past-EOF entry.
  1863  				// diag("instruction with line number past EOF in %s: %P", histfile[1], q);
  1864  				continue;
  1865  			}
  1866  
  1867  			lline = lh->line + q->line - lh->absline;
  1868  			if (debug['v'] > 1)
  1869  				print("%6llux %s[%lld] %P\n", (vlong)q->pc, histfile[lh->file], lline, q);
  1870  
  1871  			if (q->line == lc)
  1872  				continue;
  1873  			if (currfile != lh->file) {
  1874  				currfile = lh->file;
  1875  				cput(DW_LNS_set_file);
  1876  				uleb128put(currfile);
  1877  			}
  1878  			putpclcdelta(q->pc - pc, lline - llc);
  1879  			pc  = q->pc;
  1880  			lc  = q->line;
  1881  			llc = lline;
  1882  		}
  1883  
  1884  		da = 0;
  1885  		dwfunc->hash = varhash;	 // enable indexing of children by name
  1886  		memset(varhash, 0, sizeof varhash);
  1887  		for(a = s->autom; a; a = a->link) {
  1888  			switch (a->type) {
  1889  			case D_AUTO:
  1890  				dt = DW_ABRV_AUTO;
  1891  				offs = a->aoffset - PtrSize;
  1892  				break;
  1893  			case D_PARAM:
  1894  				dt = DW_ABRV_PARAM;
  1895  				offs = a->aoffset;
  1896  				break;
  1897  			default:
  1898  				continue;
  1899  			}
  1900  			if (strstr(a->asym->name, ".autotmp_"))
  1901  				continue;
  1902  			if (find(dwfunc, a->asym->name) != nil)
  1903  				n = mkvarname(a->asym->name, da);
  1904  			else
  1905  				n = a->asym->name;
  1906  			// Drop the package prefix from locals and arguments.
  1907  			nn = strrchr(n, '.');
  1908  			if (nn)
  1909  				n = nn + 1;
  1910  
  1911  			dwvar = newdie(dwfunc, dt, n);
  1912  			newcfaoffsetattr(dwvar, offs);
  1913  			newrefattr(dwvar, DW_AT_type, defgotype(a->gotype));
  1914  
  1915  			// push dwvar down dwfunc->child to preserve order
  1916  			newattr(dwvar, DW_AT_internal_location, DW_CLS_CONSTANT, offs, nil);
  1917  			dwfunc->child = dwvar->link;  // take dwvar out from the top of the list
  1918  			for (dws = &dwfunc->child; *dws != nil; dws = &(*dws)->link)
  1919  				if (offs > getattr(*dws, DW_AT_internal_location)->value)
  1920  					break;
  1921  			dwvar->link = *dws;
  1922  			*dws = dwvar;
  1923  
  1924  			da++;
  1925  		}
  1926  
  1927  		dwfunc->hash = nil;
  1928  	}
  1929  
  1930  	flushunit(dwinfo, epc, epcs, unitstart, headerend - unitstart - 10);
  1931  	linesize = cpos() - lineo;
  1932  }
  1933  
  1934  /*
  1935   *  Emit .debug_frame
  1936   */
  1937  enum
  1938  {
  1939  	CIERESERVE = 16,
  1940  	DATAALIGNMENTFACTOR = -4,	// TODO -PtrSize?
  1941  	FAKERETURNCOLUMN = 16		// TODO gdb6 doesnt like > 15?
  1942  };
  1943  
  1944  static void
  1945  putpccfadelta(vlong deltapc, vlong cfa)
  1946  {
  1947  	if (deltapc < 0x40) {
  1948  		cput(DW_CFA_advance_loc + deltapc);
  1949  	} else if (deltapc < 0x100) {
  1950  		cput(DW_CFA_advance_loc1);
  1951  		cput(deltapc);
  1952  	} else if (deltapc < 0x10000) {
  1953  		cput(DW_CFA_advance_loc2);
  1954  		WPUT(deltapc);
  1955  	} else {
  1956  		cput(DW_CFA_advance_loc4);
  1957  		LPUT(deltapc);
  1958  	}
  1959  
  1960  	cput(DW_CFA_def_cfa_offset_sf);
  1961  	sleb128put(cfa / DATAALIGNMENTFACTOR);
  1962  }
  1963  
  1964  static void
  1965  writeframes(void)
  1966  {
  1967  	Prog *p, *q;
  1968  	Sym *s;
  1969  	vlong fdeo, fdesize, pad, cfa, pc;
  1970  
  1971  	frameo = cpos();
  1972  
  1973  	// Emit the CIE, Section 6.4.1
  1974  	LPUT(CIERESERVE);	// initial length, must be multiple of PtrSize
  1975  	LPUT(0xffffffff);	// cid.
  1976  	cput(3);		// dwarf version (appendix F)
  1977  	cput(0);		// augmentation ""
  1978  	uleb128put(1);		// code_alignment_factor
  1979  	sleb128put(DATAALIGNMENTFACTOR); // guess
  1980  	uleb128put(FAKERETURNCOLUMN);	// return_address_register
  1981  
  1982  	cput(DW_CFA_def_cfa);
  1983  	uleb128put(DWARFREGSP);	// register SP (**ABI-dependent, defined in l.h)
  1984  	uleb128put(PtrSize);	// offset
  1985  
  1986  	cput(DW_CFA_offset + FAKERETURNCOLUMN);	 // return address
  1987  	uleb128put(-PtrSize / DATAALIGNMENTFACTOR);  // at cfa - x*4
  1988  
  1989  	// 4 is to exclude the length field.
  1990  	pad = CIERESERVE + frameo + 4 - cpos();
  1991  	if (pad < 0) {
  1992  		diag("dwarf: CIERESERVE too small by %lld bytes.", -pad);
  1993  		errorexit();
  1994  	}
  1995  	strnput("", pad);
  1996  
  1997  	for(cursym = textp; cursym != nil; cursym = cursym->next) {
  1998  		s = cursym;
  1999  		if(s->text == nil)
  2000  			continue;
  2001  
  2002  		fdeo = cpos();
  2003  		// Emit a FDE, Section 6.4.1, starting wit a placeholder.
  2004  		LPUT(0);	// length, must be multiple of PtrSize
  2005  		LPUT(0);	// Pointer to the CIE above, at offset 0
  2006  		addrput(0);	// initial location
  2007  		addrput(0);	// address range
  2008  
  2009  		cfa = PtrSize;	// CFA starts at sp+PtrSize
  2010  		p = s->text;
  2011  		pc = p->pc;
  2012  
  2013  		for(q = p; q->link != P; q = q->link) {
  2014  			if (q->spadj == 0)
  2015  				continue;
  2016  			cfa += q->spadj;
  2017  			putpccfadelta(q->link->pc - pc, cfa);
  2018  			pc = q->link->pc;
  2019  		}
  2020  
  2021  		fdesize = cpos() - fdeo - 4;	// exclude the length field.
  2022  		pad = rnd(fdesize, PtrSize) - fdesize;
  2023  		strnput("", pad);
  2024  		fdesize += pad;
  2025  
  2026  		// Emit the FDE header for real, Section 6.4.1.
  2027  		cseek(fdeo);
  2028  		LPUT(fdesize);
  2029  		LPUT(0);
  2030  		addrput(p->pc);
  2031  		addrput(s->size);
  2032  		cseek(fdeo + 4 + fdesize);
  2033  	}
  2034  
  2035  	cflush();
  2036  	framesize = cpos() - frameo;
  2037  }
  2038  
  2039  /*
  2040   *  Walk DWarfDebugInfoEntries, and emit .debug_info
  2041   */
  2042  enum
  2043  {
  2044  	COMPUNITHEADERSIZE = 4+2+4+1
  2045  };
  2046  
  2047  static void
  2048  writeinfo(void)
  2049  {
  2050  	DWDie *compunit;
  2051  	vlong unitstart, here;
  2052  
  2053  	fwdcount = 0;
  2054  	if (infosec == S)
  2055  		infosec = lookup(".dwarfinfo", 0);
  2056  	infosec->nr = 0;
  2057  
  2058  	if(arangessec == S)
  2059  		arangessec = lookup(".dwarfaranges", 0);
  2060  	arangessec->nr = 0;
  2061  
  2062  	for (compunit = dwroot.child; compunit; compunit = compunit->link) {
  2063  		unitstart = cpos();
  2064  
  2065  		// Write .debug_info Compilation Unit Header (sec 7.5.1)
  2066  		// Fields marked with (*) must be changed for 64-bit dwarf
  2067  		// This must match COMPUNITHEADERSIZE above.
  2068  		LPUT(0);	// unit_length (*), will be filled in later.
  2069  		WPUT(2);	// dwarf version (appendix F)
  2070  
  2071  		// debug_abbrev_offset (*)
  2072  		if(linkmode == LinkExternal)
  2073  			adddwarfrel(infosec, abbrevsym, infoo, 4, 0);
  2074  		else
  2075  			LPUT(0);
  2076  
  2077  		cput(PtrSize);	// address_size
  2078  
  2079  		putdie(compunit);
  2080  
  2081  		here = cpos();
  2082  		cseek(unitstart);
  2083  		LPUT(here - unitstart - 4);	// exclude the length field.
  2084  		cseek(here);
  2085  	}
  2086  	cflush();
  2087  }
  2088  
  2089  /*
  2090   *  Emit .debug_pubnames/_types.  _info must have been written before,
  2091   *  because we need die->offs and infoo/infosize;
  2092   */
  2093  static int
  2094  ispubname(DWDie *die)
  2095  {
  2096  	DWAttr *a;
  2097  
  2098  	switch(die->abbrev) {
  2099  	case DW_ABRV_FUNCTION:
  2100  	case DW_ABRV_VARIABLE:
  2101  		a = getattr(die, DW_AT_external);
  2102  		return a && a->value;
  2103  	}
  2104  	return 0;
  2105  }
  2106  
  2107  static int
  2108  ispubtype(DWDie *die)
  2109  {
  2110  	return die->abbrev >= DW_ABRV_NULLTYPE;
  2111  }
  2112  
  2113  static vlong
  2114  writepub(int (*ispub)(DWDie*))
  2115  {
  2116  	DWDie *compunit, *die;
  2117  	DWAttr *dwa;
  2118  	vlong unitstart, unitend, sectionstart, here;
  2119  
  2120  	sectionstart = cpos();
  2121  
  2122  	for (compunit = dwroot.child; compunit != nil; compunit = compunit->link) {
  2123  		unitstart = compunit->offs - COMPUNITHEADERSIZE;
  2124  		if (compunit->link != nil)
  2125  			unitend = compunit->link->offs - COMPUNITHEADERSIZE;
  2126  		else
  2127  			unitend = infoo + infosize;
  2128  
  2129  		// Write .debug_pubnames/types	Header (sec 6.1.1)
  2130  		LPUT(0);			// unit_length (*), will be filled in later.
  2131  		WPUT(2);			// dwarf version (appendix F)
  2132  		LPUT(unitstart);		// debug_info_offset (of the Comp unit Header)
  2133  		LPUT(unitend - unitstart);	// debug_info_length
  2134  
  2135  		for (die = compunit->child; die != nil; die = die->link) {
  2136  			if (!ispub(die)) continue;
  2137  			LPUT(die->offs - unitstart);
  2138  			dwa = getattr(die, DW_AT_name);
  2139  			strnput(dwa->data, dwa->value + 1);
  2140  		}
  2141  		LPUT(0);
  2142  
  2143  		here = cpos();
  2144  		cseek(sectionstart);
  2145  		LPUT(here - sectionstart - 4);	// exclude the length field.
  2146  		cseek(here);
  2147  
  2148  	}
  2149  
  2150  	return sectionstart;
  2151  }
  2152  
  2153  /*
  2154   *  emit .debug_aranges.  _info must have been written before,
  2155   *  because we need die->offs of dw_globals.
  2156   */
  2157  static vlong
  2158  writearanges(void)
  2159  {
  2160  	DWDie *compunit;
  2161  	DWAttr *b, *e;
  2162  	int headersize;
  2163  	vlong sectionstart;
  2164  	vlong value;
  2165  
  2166  	sectionstart = cpos();
  2167  	headersize = rnd(4+2+4+1+1, PtrSize);  // don't count unit_length field itself
  2168  
  2169  	for (compunit = dwroot.child; compunit != nil; compunit = compunit->link) {
  2170  		b = getattr(compunit,  DW_AT_low_pc);
  2171  		if (b == nil)
  2172  			continue;
  2173  		e = getattr(compunit,  DW_AT_high_pc);
  2174  		if (e == nil)
  2175  			continue;
  2176  
  2177  		// Write .debug_aranges	 Header + entry	 (sec 6.1.2)
  2178  		LPUT(headersize + 4*PtrSize - 4);	// unit_length (*)
  2179  		WPUT(2);	// dwarf version (appendix F)
  2180  
  2181  		value = compunit->offs - COMPUNITHEADERSIZE;	// debug_info_offset
  2182  		if(linkmode == LinkExternal)
  2183  			adddwarfrel(arangessec, infosym, sectionstart, 4, value);
  2184  		else
  2185  			LPUT(value);
  2186  
  2187  		cput(PtrSize);	// address_size
  2188  		cput(0);	// segment_size
  2189  		strnput("", headersize - (4+2+4+1+1));	// align to PtrSize
  2190  
  2191  		if(linkmode == LinkExternal)
  2192  			adddwarfrel(arangessec, (Sym*)b->data, sectionstart, PtrSize, b->value-((Sym*)b->data)->value);
  2193  		else
  2194  			addrput(b->value);
  2195  
  2196  		addrput(e->value - b->value);
  2197  		addrput(0);
  2198  		addrput(0);
  2199  	}
  2200  	cflush();
  2201  	return sectionstart;
  2202  }
  2203  
  2204  static vlong
  2205  writegdbscript(void)
  2206  {
  2207  	vlong sectionstart;
  2208  
  2209  	sectionstart = cpos();
  2210  
  2211  	if (gdbscript[0]) {
  2212  		cput(1);  // magic 1 byte?
  2213  		strnput(gdbscript, strlen(gdbscript)+1);
  2214  		cflush();
  2215  	}
  2216  	return sectionstart;
  2217  }
  2218  
  2219  static void
  2220  align(vlong size)
  2221  {
  2222  	if(HEADTYPE == Hwindows) // Only Windows PE need section align.
  2223  		strnput("", rnd(size, PEFILEALIGN) - size);
  2224  }
  2225  
  2226  static vlong
  2227  writedwarfreloc(Sym* s)
  2228  {
  2229  	int i;
  2230  	vlong start;
  2231  	Reloc *r;
  2232  	
  2233  	start = cpos();
  2234  	for(r = s->r; r < s->r+s->nr; r++) {
  2235  		if(iself)
  2236  			i = elfreloc1(r, r->off);
  2237  		else if(HEADTYPE == Hdarwin)
  2238  			i = machoreloc1(r, r->off);
  2239  		else
  2240  			i = -1;
  2241  		if(i < 0)
  2242  			diag("unsupported obj reloc %d/%d to %s", r->type, r->siz, r->sym->name);
  2243  	}
  2244  	return start;
  2245  }
  2246  
  2247  /*
  2248   * This is the main entry point for generating dwarf.  After emitting
  2249   * the mandatory debug_abbrev section, it calls writelines() to set up
  2250   * the per-compilation unit part of the DIE tree, while simultaneously
  2251   * emitting the debug_line section.  When the final tree contains
  2252   * forward references, it will write the debug_info section in 2
  2253   * passes.
  2254   *
  2255   */
  2256  void
  2257  dwarfemitdebugsections(void)
  2258  {
  2259  	vlong infoe;
  2260  	DWDie* die;
  2261  
  2262  	if(debug['w'])  // disable dwarf
  2263  		return;
  2264  
  2265  	if(linkmode == LinkExternal && !iself)
  2266  		return;
  2267  
  2268  	// For diagnostic messages.
  2269  	newattr(&dwtypes, DW_AT_name, DW_CLS_STRING, strlen("dwtypes"), "dwtypes");
  2270  
  2271  	mkindex(&dwroot);
  2272  	mkindex(&dwtypes);
  2273  	mkindex(&dwglobals);
  2274  
  2275  	// Some types that must exist to define other ones.
  2276  	newdie(&dwtypes, DW_ABRV_NULLTYPE, "<unspecified>");
  2277  	newdie(&dwtypes, DW_ABRV_NULLTYPE, "void");
  2278  	newdie(&dwtypes, DW_ABRV_BARE_PTRTYPE, "unsafe.Pointer");
  2279  	die = newdie(&dwtypes, DW_ABRV_BASETYPE, "uintptr");  // needed for array size
  2280  	newattr(die, DW_AT_encoding,  DW_CLS_CONSTANT, DW_ATE_unsigned, 0);
  2281  	newattr(die, DW_AT_byte_size, DW_CLS_CONSTANT, PtrSize, 0);
  2282  
  2283  	// Needed by the prettyprinter code for interface inspection.
  2284  	defgotype(lookup_or_diag("type.runtime.rtype"));
  2285  	defgotype(lookup_or_diag("type.runtime.interfaceType"));
  2286  	defgotype(lookup_or_diag("type.runtime.itab"));
  2287  
  2288  	genasmsym(defdwsymb);
  2289  
  2290  	writeabbrev();
  2291  	align(abbrevsize);
  2292  	writelines();
  2293  	align(linesize);
  2294  	writeframes();
  2295  	align(framesize);
  2296  
  2297  	synthesizestringtypes(dwtypes.child);
  2298  	synthesizeslicetypes(dwtypes.child);
  2299  	synthesizemaptypes(dwtypes.child);
  2300  	synthesizechantypes(dwtypes.child);
  2301  
  2302  	reversetree(&dwroot.child);
  2303  	reversetree(&dwtypes.child);
  2304  	reversetree(&dwglobals.child);
  2305  
  2306  	movetomodule(&dwtypes);
  2307  	movetomodule(&dwglobals);
  2308  
  2309  	infoo = cpos();
  2310  	writeinfo();
  2311  	infoe = cpos();
  2312  	pubnameso = infoe;
  2313  	pubtypeso = infoe;
  2314  	arangeso = infoe;
  2315  	gdbscripto = infoe;
  2316  
  2317  	if (fwdcount > 0) {
  2318  		if (debug['v'])
  2319  			Bprint(&bso, "%5.2f dwarf pass 2.\n", cputime());
  2320  		cseek(infoo);
  2321  		writeinfo();
  2322  		if (fwdcount > 0) {
  2323  			diag("dwarf: unresolved references after first dwarf info pass");
  2324  			errorexit();
  2325  		}
  2326  		if (infoe != cpos()) {
  2327  			diag("dwarf: inconsistent second dwarf info pass");
  2328  			errorexit();
  2329  		}
  2330  	}
  2331  	infosize = infoe - infoo;
  2332  	align(infosize);
  2333  
  2334  	pubnameso  = writepub(ispubname);
  2335  	pubnamessize  = cpos() - pubnameso;
  2336  	align(pubnamessize);
  2337  
  2338  	pubtypeso  = writepub(ispubtype);
  2339  	pubtypessize  = cpos() - pubtypeso;
  2340  	align(pubtypessize);
  2341  
  2342  	arangeso   = writearanges();
  2343  	arangessize   = cpos() - arangeso;
  2344  	align(arangessize);
  2345  
  2346  	gdbscripto = writegdbscript();
  2347  	gdbscriptsize = cpos() - gdbscripto;
  2348  	align(gdbscriptsize);
  2349  
  2350  	while(cpos()&7)
  2351  		cput(0);
  2352  	inforeloco = writedwarfreloc(infosec);
  2353  	inforelocsize = cpos() - inforeloco;
  2354  	align(inforelocsize);
  2355  
  2356  	arangesreloco = writedwarfreloc(arangessec);
  2357  	arangesrelocsize = cpos() - arangesreloco;
  2358  	align(arangesrelocsize);
  2359  
  2360  	linereloco = writedwarfreloc(linesec);
  2361  	linerelocsize = cpos() - linereloco;
  2362  	align(linerelocsize);
  2363  }
  2364  
  2365  /*
  2366   *  Elf.
  2367   */
  2368  enum
  2369  {
  2370  	ElfStrDebugAbbrev,
  2371  	ElfStrDebugAranges,
  2372  	ElfStrDebugFrame,
  2373  	ElfStrDebugInfo,
  2374  	ElfStrDebugLine,
  2375  	ElfStrDebugLoc,
  2376  	ElfStrDebugMacinfo,
  2377  	ElfStrDebugPubNames,
  2378  	ElfStrDebugPubTypes,
  2379  	ElfStrDebugRanges,
  2380  	ElfStrDebugStr,
  2381  	ElfStrGDBScripts,
  2382  	ElfStrRelDebugInfo,
  2383  	ElfStrRelDebugAranges,
  2384  	ElfStrRelDebugLine,
  2385  	NElfStrDbg
  2386  };
  2387  
  2388  vlong elfstrdbg[NElfStrDbg];
  2389  
  2390  void
  2391  dwarfaddshstrings(Sym *shstrtab)
  2392  {
  2393  	if(debug['w'])  // disable dwarf
  2394  		return;
  2395  
  2396  	elfstrdbg[ElfStrDebugAbbrev]   = addstring(shstrtab, ".debug_abbrev");
  2397  	elfstrdbg[ElfStrDebugAranges]  = addstring(shstrtab, ".debug_aranges");
  2398  	elfstrdbg[ElfStrDebugFrame]    = addstring(shstrtab, ".debug_frame");
  2399  	elfstrdbg[ElfStrDebugInfo]     = addstring(shstrtab, ".debug_info");
  2400  	elfstrdbg[ElfStrDebugLine]     = addstring(shstrtab, ".debug_line");
  2401  	elfstrdbg[ElfStrDebugLoc]      = addstring(shstrtab, ".debug_loc");
  2402  	elfstrdbg[ElfStrDebugMacinfo]  = addstring(shstrtab, ".debug_macinfo");
  2403  	elfstrdbg[ElfStrDebugPubNames] = addstring(shstrtab, ".debug_pubnames");
  2404  	elfstrdbg[ElfStrDebugPubTypes] = addstring(shstrtab, ".debug_pubtypes");
  2405  	elfstrdbg[ElfStrDebugRanges]   = addstring(shstrtab, ".debug_ranges");
  2406  	elfstrdbg[ElfStrDebugStr]      = addstring(shstrtab, ".debug_str");
  2407  	elfstrdbg[ElfStrGDBScripts]    = addstring(shstrtab, ".debug_gdb_scripts");
  2408  	if(linkmode == LinkExternal) {
  2409  		if(thechar == '6') {
  2410  			elfstrdbg[ElfStrRelDebugInfo] = addstring(shstrtab, ".rela.debug_info");
  2411  			elfstrdbg[ElfStrRelDebugAranges] = addstring(shstrtab, ".rela.debug_aranges");
  2412  			elfstrdbg[ElfStrRelDebugLine] = addstring(shstrtab, ".rela.debug_line");
  2413  		} else {
  2414  			elfstrdbg[ElfStrRelDebugInfo] = addstring(shstrtab, ".rel.debug_info");
  2415  			elfstrdbg[ElfStrRelDebugAranges] = addstring(shstrtab, ".rel.debug_aranges");
  2416  			elfstrdbg[ElfStrRelDebugLine] = addstring(shstrtab, ".rel.debug_line");
  2417  		}
  2418  
  2419  		infosym = lookup(".debug_info", 0);
  2420  		infosym->hide = 1;
  2421  
  2422  		abbrevsym = lookup(".debug_abbrev", 0);
  2423  		abbrevsym->hide = 1;
  2424  
  2425  		linesym = lookup(".debug_line", 0);
  2426  		linesym->hide = 1;
  2427  	}
  2428  }
  2429  
  2430  // Add section symbols for DWARF debug info.  This is called before
  2431  // dwarfaddelfheaders.
  2432  void
  2433  dwarfaddelfsectionsyms()
  2434  {
  2435  	if(infosym != nil) {
  2436  		infosympos = cpos();
  2437  		putelfsectionsym(infosym, 0);
  2438  	}
  2439  	if(abbrevsym != nil) {
  2440  		abbrevsympos = cpos();
  2441  		putelfsectionsym(abbrevsym, 0);
  2442  	}
  2443  	if(linesym != nil) {
  2444  		linesympos = cpos();
  2445  		putelfsectionsym(linesym, 0);
  2446  	}
  2447  }
  2448  
  2449  static void
  2450  dwarfaddelfrelocheader(int elfstr, ElfShdr *shdata, vlong off, vlong size)
  2451  {
  2452  	ElfShdr *sh;
  2453  
  2454  	sh = newElfShdr(elfstrdbg[elfstr]);
  2455  	if(thechar == '6') {
  2456  		sh->type = SHT_RELA;
  2457  	} else {
  2458  		sh->type = SHT_REL;
  2459  	}
  2460  	sh->entsize = PtrSize*(2+(sh->type==SHT_RELA));
  2461  	sh->link = elfshname(".symtab")->shnum;
  2462  	sh->info = shdata->shnum;
  2463  	sh->off = off;
  2464  	sh->size = size;
  2465  	sh->addralign = PtrSize;
  2466  	
  2467  }
  2468  
  2469  void
  2470  dwarfaddelfheaders(void)
  2471  {
  2472  	ElfShdr *sh, *shinfo, *sharanges, *shline;
  2473  
  2474  	if(debug['w'])  // disable dwarf
  2475  		return;
  2476  
  2477  	sh = newElfShdr(elfstrdbg[ElfStrDebugAbbrev]);
  2478  	sh->type = SHT_PROGBITS;
  2479  	sh->off = abbrevo;
  2480  	sh->size = abbrevsize;
  2481  	sh->addralign = 1;
  2482  	if(abbrevsympos > 0)
  2483  		putelfsymshndx(abbrevsympos, sh->shnum);
  2484  
  2485  	sh = newElfShdr(elfstrdbg[ElfStrDebugLine]);
  2486  	sh->type = SHT_PROGBITS;
  2487  	sh->off = lineo;
  2488  	sh->size = linesize;
  2489  	sh->addralign = 1;
  2490  	if(linesympos > 0)
  2491  		putelfsymshndx(linesympos, sh->shnum);
  2492  	shline = sh;
  2493  
  2494  	sh = newElfShdr(elfstrdbg[ElfStrDebugFrame]);
  2495  	sh->type = SHT_PROGBITS;
  2496  	sh->off = frameo;
  2497  	sh->size = framesize;
  2498  	sh->addralign = 1;
  2499  
  2500  	sh = newElfShdr(elfstrdbg[ElfStrDebugInfo]);
  2501  	sh->type = SHT_PROGBITS;
  2502  	sh->off = infoo;
  2503  	sh->size = infosize;
  2504  	sh->addralign = 1;
  2505  	if(infosympos > 0)
  2506  		putelfsymshndx(infosympos, sh->shnum);
  2507  	shinfo = sh;
  2508  
  2509  	if (pubnamessize > 0) {
  2510  		sh = newElfShdr(elfstrdbg[ElfStrDebugPubNames]);
  2511  		sh->type = SHT_PROGBITS;
  2512  		sh->off = pubnameso;
  2513  		sh->size = pubnamessize;
  2514  		sh->addralign = 1;
  2515  	}
  2516  
  2517  	if (pubtypessize > 0) {
  2518  		sh = newElfShdr(elfstrdbg[ElfStrDebugPubTypes]);
  2519  		sh->type = SHT_PROGBITS;
  2520  		sh->off = pubtypeso;
  2521  		sh->size = pubtypessize;
  2522  		sh->addralign = 1;
  2523  	}
  2524  
  2525  	sharanges = nil;
  2526  	if (arangessize) {
  2527  		sh = newElfShdr(elfstrdbg[ElfStrDebugAranges]);
  2528  		sh->type = SHT_PROGBITS;
  2529  		sh->off = arangeso;
  2530  		sh->size = arangessize;
  2531  		sh->addralign = 1;
  2532  		sharanges = sh;
  2533  	}
  2534  
  2535  	if (gdbscriptsize) {
  2536  		sh = newElfShdr(elfstrdbg[ElfStrGDBScripts]);
  2537  		sh->type = SHT_PROGBITS;
  2538  		sh->off = gdbscripto;
  2539  		sh->size = gdbscriptsize;
  2540  		sh->addralign = 1;
  2541  	}
  2542  
  2543  	if(inforelocsize)
  2544  		dwarfaddelfrelocheader(ElfStrRelDebugInfo, shinfo, inforeloco, inforelocsize);
  2545  
  2546  	if(arangesrelocsize)
  2547  		dwarfaddelfrelocheader(ElfStrRelDebugAranges, sharanges, arangesreloco, arangesrelocsize);
  2548  
  2549  	if(linerelocsize)
  2550  		dwarfaddelfrelocheader(ElfStrRelDebugLine, shline, linereloco, linerelocsize);
  2551  }
  2552  
  2553  /*
  2554   * Macho
  2555   */
  2556  void
  2557  dwarfaddmachoheaders(void)
  2558  {
  2559  	MachoSect *msect;
  2560  	MachoSeg *ms;
  2561  	vlong fakestart;
  2562  	int nsect;
  2563  
  2564  	if(debug['w'])  // disable dwarf
  2565  		return;
  2566  
  2567  	// Zero vsize segments won't be loaded in memory, even so they
  2568  	// have to be page aligned in the file.
  2569  	fakestart = abbrevo & ~0xfff;
  2570  
  2571  	nsect = 4;
  2572  	if (pubnamessize  > 0)
  2573  		nsect++;
  2574  	if (pubtypessize  > 0)
  2575  		nsect++;
  2576  	if (arangessize	  > 0)
  2577  		nsect++;
  2578  	if (gdbscriptsize > 0)
  2579  		nsect++;
  2580  
  2581  	ms = newMachoSeg("__DWARF", nsect);
  2582  	ms->fileoffset = fakestart;
  2583  	ms->filesize = abbrevo-fakestart;
  2584  
  2585  	msect = newMachoSect(ms, "__debug_abbrev", "__DWARF");
  2586  	msect->off = abbrevo;
  2587  	msect->size = abbrevsize;
  2588  	ms->filesize += msect->size;
  2589  
  2590  	msect = newMachoSect(ms, "__debug_line", "__DWARF");
  2591  	msect->off = lineo;
  2592  	msect->size = linesize;
  2593  	ms->filesize += msect->size;
  2594  
  2595  	msect = newMachoSect(ms, "__debug_frame", "__DWARF");
  2596  	msect->off = frameo;
  2597  	msect->size = framesize;
  2598  	ms->filesize += msect->size;
  2599  
  2600  	msect = newMachoSect(ms, "__debug_info", "__DWARF");
  2601  	msect->off = infoo;
  2602  	msect->size = infosize;
  2603  	ms->filesize += msect->size;
  2604  
  2605  	if (pubnamessize > 0) {
  2606  		msect = newMachoSect(ms, "__debug_pubnames", "__DWARF");
  2607  		msect->off = pubnameso;
  2608  		msect->size = pubnamessize;
  2609  		ms->filesize += msect->size;
  2610  	}
  2611  
  2612  	if (pubtypessize > 0) {
  2613  		msect = newMachoSect(ms, "__debug_pubtypes", "__DWARF");
  2614  		msect->off = pubtypeso;
  2615  		msect->size = pubtypessize;
  2616  		ms->filesize += msect->size;
  2617  	}
  2618  
  2619  	if (arangessize > 0) {
  2620  		msect = newMachoSect(ms, "__debug_aranges", "__DWARF");
  2621  		msect->off = arangeso;
  2622  		msect->size = arangessize;
  2623  		ms->filesize += msect->size;
  2624  	}
  2625  
  2626  	// TODO(lvd) fix gdb/python to load MachO (16 char section name limit)
  2627  	if (gdbscriptsize > 0) {
  2628  		msect = newMachoSect(ms, "__debug_gdb_scripts", "__DWARF");
  2629  		msect->off = gdbscripto;
  2630  		msect->size = gdbscriptsize;
  2631  		ms->filesize += msect->size;
  2632  	}
  2633  }
  2634  
  2635  /*
  2636   * Windows PE
  2637   */
  2638  void
  2639  dwarfaddpeheaders(void)
  2640  {
  2641  	if(debug['w'])  // disable dwarf
  2642  		return;
  2643  
  2644  	newPEDWARFSection(".debug_abbrev", abbrevsize);
  2645  	newPEDWARFSection(".debug_line", linesize);
  2646  	newPEDWARFSection(".debug_frame", framesize);
  2647  	newPEDWARFSection(".debug_info", infosize);
  2648  	newPEDWARFSection(".debug_pubnames", pubnamessize);
  2649  	newPEDWARFSection(".debug_pubtypes", pubtypessize);
  2650  	newPEDWARFSection(".debug_aranges", arangessize);
  2651  	newPEDWARFSection(".debug_gdb_scripts", gdbscriptsize);
  2652  }