Source file src/runtime/print.go

     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  package runtime
     6  
     7  import (
     8  	"internal/strconv"
     9  	"unsafe"
    10  )
    11  
    12  // The compiler knows that a print of a value of this type
    13  // should use printhex instead of printuint (decimal).
    14  type hex uint64
    15  
    16  // The compiler knows that a print of a value of this type should use
    17  // printquoted instead of printstring.
    18  type quoted string
    19  
    20  func bytes(s string) (ret []byte) {
    21  	rp := (*slice)(unsafe.Pointer(&ret))
    22  	sp := stringStructOf(&s)
    23  	rp.array = sp.str
    24  	rp.len = sp.len
    25  	rp.cap = sp.len
    26  	return
    27  }
    28  
    29  var (
    30  	// printBacklog is a circular buffer of messages written with the builtin
    31  	// print* functions, for use in postmortem analysis of core dumps.
    32  	printBacklog      [512]byte
    33  	printBacklogIndex int
    34  )
    35  
    36  // recordForPanic maintains a circular buffer of messages written by the
    37  // runtime leading up to a process crash, allowing the messages to be
    38  // extracted from a core dump.
    39  //
    40  // The text written during a process crash (following "panic" or "fatal
    41  // error") is not saved, since the goroutine stacks will generally be readable
    42  // from the runtime data structures in the core file.
    43  func recordForPanic(b []byte) {
    44  	printlock()
    45  
    46  	if panicking.Load() == 0 {
    47  		// Not actively crashing: maintain circular buffer of print output.
    48  		for i := 0; i < len(b); {
    49  			n := copy(printBacklog[printBacklogIndex:], b[i:])
    50  			i += n
    51  			printBacklogIndex += n
    52  			printBacklogIndex %= len(printBacklog)
    53  		}
    54  	}
    55  
    56  	printunlock()
    57  }
    58  
    59  var debuglock mutex
    60  
    61  // The compiler emits calls to printlock and printunlock around
    62  // the multiple calls that implement a single Go print or println
    63  // statement. Some of the print helpers (printslice, for example)
    64  // call print recursively. There is also the problem of a crash
    65  // happening during the print routines and needing to acquire
    66  // the print lock to print information about the crash.
    67  // For both these reasons, let a thread acquire the printlock 'recursively'.
    68  
    69  func printlock() {
    70  	gp := getg()
    71  	if gp.m.writebufg.ptr() == gp && gp.m.dying == 0 {
    72  		// Output is being diverted into this goroutine's own buffer
    73  		// (see gwrite), so there is nothing shared to protect. Once
    74  		// the M is dying gwrite writes to stderr instead, so keep the lock.
    75  		return
    76  	}
    77  	mp := gp.m
    78  	mp.locks++ // do not reschedule between printlock++ and lock(&debuglock).
    79  	mp.printlock++
    80  	if mp.printlock == 1 {
    81  		lock(&debuglock)
    82  	}
    83  	mp.locks-- // now we know debuglock is held and holding up mp.locks for us.
    84  }
    85  
    86  func printunlock() {
    87  	gp := getg()
    88  	if gp.m.writebufg.ptr() == gp && gp.m.dying == 0 {
    89  		return
    90  	}
    91  	mp := gp.m
    92  	mp.printlock--
    93  	if mp.printlock == 0 {
    94  		unlock(&debuglock)
    95  	}
    96  }
    97  
    98  // write to the M's writebuf if diverting this goroutine's output,
    99  // or else standard error.
   100  func gwrite(b []byte) {
   101  	if len(b) == 0 {
   102  		return
   103  	}
   104  	gp := getg()
   105  	// Don't use the writebuf if gp.m is dying. We want anything
   106  	// written through gwrite to appear in the terminal rather
   107  	// than be written to in some buffer, if we're in a panicking state.
   108  	// Note that we can't just clear writebuf in the gp.m.dying case
   109  	// because a panic isn't allowed to have any write barriers.
   110  	if gp == nil || gp.m.writebufg.ptr() != gp || gp.m.dying > 0 {
   111  		recordForPanic(b)
   112  		writeErr(b)
   113  		return
   114  	}
   115  
   116  	mp := gp.m
   117  	n := copy(mp.writebuf[len(mp.writebuf):cap(mp.writebuf)], b)
   118  	mp.writebuf = mp.writebuf[:len(mp.writebuf)+n]
   119  }
   120  
   121  func printsp() {
   122  	printstring(" ")
   123  }
   124  
   125  func printnl() {
   126  	printstring("\n")
   127  }
   128  
   129  func printbool(v bool) {
   130  	if v {
   131  		printstring("true")
   132  	} else {
   133  		printstring("false")
   134  	}
   135  }
   136  
   137  // float64 requires 1+17+1+1+1+3 = 24 bytes max (sign+digits+decimal point+e+sign+exponent digits).
   138  const float64Bytes = 24
   139  
   140  func printfloat64(v float64) {
   141  	var buf [float64Bytes]byte
   142  	gwrite(strconv.AppendFloat(buf[:0], v, 'g', -1, 64))
   143  }
   144  
   145  // float32 requires 1+9+1+1+1+2 = 15 bytes max (sign+digits+decimal point+e+sign+exponent digits).
   146  const float32Bytes = 15
   147  
   148  func printfloat32(v float32) {
   149  	var buf [float32Bytes]byte
   150  	gwrite(strconv.AppendFloat(buf[:0], float64(v), 'g', -1, 32))
   151  }
   152  
   153  // complex128 requires 24+24+1+1+1 = 51 bytes max (paren+float64+float64+i+paren).
   154  const complex128Bytes = 2*float64Bytes + 3
   155  
   156  func printcomplex128(c complex128) {
   157  	var buf [complex128Bytes]byte
   158  	gwrite(strconv.AppendComplex(buf[:0], c, 'g', -1, 128))
   159  }
   160  
   161  // complex64 requires 15+15+1+1+1 = 33 bytes max (paren+float32+float32+i+paren).
   162  const complex64Bytes = 2*float32Bytes + 3
   163  
   164  func printcomplex64(c complex64) {
   165  	var buf [complex64Bytes]byte
   166  	gwrite(strconv.AppendComplex(buf[:0], complex128(c), 'g', -1, 64))
   167  }
   168  
   169  func printuint(v uint64) {
   170  	// Note: Avoiding strconv.AppendUint so that it's clearer
   171  	// that there are no allocations in this routine.
   172  	// cmd/link/internal/ld.TestAbstractOriginSanity
   173  	// sees the append and doesn't realize it doesn't allocate.
   174  	var buf [20]byte
   175  	i := strconv.RuntimeFormatBase10(buf[:], v)
   176  	gwrite(buf[i:])
   177  }
   178  
   179  func printint(v int64) {
   180  	// Note: Avoiding strconv.AppendUint so that it's clearer
   181  	// that there are no allocations in this routine.
   182  	// cmd/link/internal/ld.TestAbstractOriginSanity
   183  	// sees the append and doesn't realize it doesn't allocate.
   184  	neg := v < 0
   185  	u := uint64(v)
   186  	if neg {
   187  		u = -u
   188  	}
   189  	var buf [20]byte
   190  	i := strconv.RuntimeFormatBase10(buf[:], u)
   191  	if neg {
   192  		i--
   193  		buf[i] = '-'
   194  	}
   195  	gwrite(buf[i:])
   196  }
   197  
   198  var minhexdigits = 0 // protected by printlock
   199  
   200  func printhexopts(include0x bool, mindigits int, v uint64) {
   201  	const dig = "0123456789abcdef"
   202  	var buf [100]byte
   203  	i := len(buf)
   204  	for i--; i > 0; i-- {
   205  		buf[i] = dig[v%16]
   206  		if v < 16 && len(buf)-i >= mindigits {
   207  			break
   208  		}
   209  		v /= 16
   210  	}
   211  	if include0x {
   212  		i--
   213  		buf[i] = 'x'
   214  		i--
   215  		buf[i] = '0'
   216  	}
   217  	gwrite(buf[i:])
   218  }
   219  
   220  func printhex(v uint64) {
   221  	printhexopts(true, minhexdigits, v)
   222  }
   223  
   224  func printquoted(s string) {
   225  	printlock()
   226  	gwrite([]byte(`"`))
   227  	for i, r := range s {
   228  		switch r {
   229  		case '\n':
   230  			gwrite([]byte(`\n`))
   231  			continue
   232  		case '\r':
   233  			gwrite([]byte(`\r`))
   234  			continue
   235  		case '\t':
   236  			gwrite([]byte(`\t`))
   237  			print()
   238  			continue
   239  		case '\\', '"':
   240  			gwrite([]byte{byte('\\'), byte(r)})
   241  			continue
   242  		case runeError:
   243  			// Distinguish errors from a valid encoding of U+FFFD.
   244  			if _, j := decoderune(s, uint(i)); j == uint(i+1) {
   245  				gwrite(bytes(`\x`))
   246  				printhexopts(false, 2, uint64(s[i]))
   247  				continue
   248  			}
   249  			// Fall through to quoting.
   250  		}
   251  		// For now, only allow basic printable ascii through unescaped
   252  		if r >= ' ' && r <= '~' {
   253  			gwrite([]byte{byte(r)})
   254  		} else if r < 127 {
   255  			gwrite(bytes(`\x`))
   256  			printhexopts(false, 2, uint64(r))
   257  		} else if r < 0x1_0000 {
   258  			gwrite(bytes(`\u`))
   259  			printhexopts(false, 4, uint64(r))
   260  		} else {
   261  			gwrite(bytes(`\U`))
   262  			printhexopts(false, 8, uint64(r))
   263  		}
   264  	}
   265  	gwrite([]byte{byte('"')})
   266  	printunlock()
   267  }
   268  
   269  func printpointer(p unsafe.Pointer) {
   270  	printhex(uint64(uintptr(p)))
   271  }
   272  func printuintptr(p uintptr) {
   273  	printhex(uint64(p))
   274  }
   275  
   276  func printstring(s string) {
   277  	gwrite(bytes(s))
   278  }
   279  
   280  func printslice(s []byte) {
   281  	sp := (*slice)(unsafe.Pointer(&s))
   282  	print("[", len(s), "/", cap(s), "]")
   283  	printpointer(sp.array)
   284  }
   285  
   286  func printeface(e eface) {
   287  	print("(", e._type, ",", e.data, ")")
   288  }
   289  
   290  func printiface(i iface) {
   291  	print("(", i.tab, ",", i.data, ")")
   292  }
   293  

View as plain text