Source file src/runtime/error.go

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package runtime
     6  
     7  import (
     8  	"internal/abi"
     9  	"internal/bytealg"
    10  	"internal/runtime/sys"
    11  )
    12  
    13  // Error identifies a runtime error used in panic.
    14  //
    15  // The Go runtime triggers panics for a variety of cases, as described by the
    16  // Go Language Spec, such as out-of-bounds slice/array access, close of nil
    17  // channels, type assertion failures, etc.
    18  //
    19  // When these cases occur, the Go runtime panics with an error that implements
    20  // Error. This can be useful when recovering from panics to distinguish between
    21  // custom application panics and fundamental runtime panics.
    22  //
    23  // Packages outside of the Go standard library should not implement Error.
    24  type Error interface {
    25  	error
    26  
    27  	// RuntimeError is a no-op function but
    28  	// serves to distinguish types that are runtime
    29  	// errors from ordinary errors: a type is a
    30  	// runtime error if it has a RuntimeError method.
    31  	RuntimeError()
    32  }
    33  
    34  // A TypeAssertionError explains a failed type assertion.
    35  type TypeAssertionError struct {
    36  	_interface    *_type
    37  	concrete      *_type
    38  	asserted      *_type
    39  	missingMethod string // one method needed by Interface, missing from Concrete
    40  }
    41  
    42  func (*TypeAssertionError) RuntimeError() {}
    43  
    44  func (e *TypeAssertionError) Error() string {
    45  	inter := "interface"
    46  	if e._interface != nil {
    47  		inter = toRType(e._interface).string()
    48  	}
    49  	as := toRType(e.asserted).string()
    50  	if e.concrete == nil {
    51  		return "interface conversion: " + inter + " is nil, not " + as
    52  	}
    53  	cs := toRType(e.concrete).string()
    54  	if e.missingMethod == "" {
    55  		msg := "interface conversion: " + inter + " is " + cs + ", not " + as
    56  		if cs == as {
    57  			// provide slightly clearer error message
    58  			if toRType(e.concrete).pkgpath() != toRType(e.asserted).pkgpath() {
    59  				msg += " (types from different packages)"
    60  			} else {
    61  				msg += " (types from different scopes)"
    62  			}
    63  		}
    64  		return msg
    65  	}
    66  	return "interface conversion: " + cs + " is not " + as +
    67  		": missing method " + e.missingMethod
    68  }
    69  
    70  // itoa converts val to a decimal representation. The result is
    71  // written somewhere within buf and the location of the result is returned.
    72  // buf must be at least 20 bytes.
    73  //
    74  //go:nosplit
    75  func itoa(buf []byte, val uint64) []byte {
    76  	i := len(buf) - 1
    77  	for val >= 10 {
    78  		buf[i] = byte(val%10 + '0')
    79  		i--
    80  		val /= 10
    81  	}
    82  	buf[i] = byte(val + '0')
    83  	return buf[i:]
    84  }
    85  
    86  // An errorString represents a runtime error described by a single string.
    87  type errorString string
    88  
    89  func (e errorString) RuntimeError() {}
    90  
    91  func (e errorString) Error() string {
    92  	return "runtime error: " + string(e)
    93  }
    94  
    95  type errorAddressString struct {
    96  	msg  string  // error message
    97  	addr uintptr // memory address where the error occurred
    98  }
    99  
   100  func (e errorAddressString) RuntimeError() {}
   101  
   102  func (e errorAddressString) Error() string {
   103  	return "runtime error: " + e.msg
   104  }
   105  
   106  var _ error = errorAddressString{}
   107  
   108  // Addr returns the memory address where a fault occurred.
   109  // The address provided is best-effort.
   110  // The veracity of the result may depend on the platform.
   111  // Errors providing this method will only be returned as
   112  // a result of using [runtime/debug.SetPanicOnFault].
   113  func (e errorAddressString) Addr() uintptr {
   114  	return e.addr
   115  }
   116  
   117  // plainError represents a runtime error described a string without
   118  // the prefix "runtime error: " after invoking errorString.Error().
   119  // See Issue #14965.
   120  type plainError string
   121  
   122  func (e plainError) RuntimeError() {}
   123  
   124  func (e plainError) Error() string {
   125  	return string(e)
   126  }
   127  
   128  var _ error = plainError("")
   129  
   130  // A boundsError represents an indexing or slicing operation gone wrong.
   131  type boundsError struct {
   132  	x int64
   133  	y int
   134  	// Values in an index or slice expression can be signed or unsigned.
   135  	// That means we'd need 65 bits to encode all possible indexes, from -2^63 to 2^64-1.
   136  	// Instead, we keep track of whether x should be interpreted as signed or unsigned.
   137  	// y is known to be nonnegative and to fit in an int.
   138  	signed bool
   139  	code   abi.BoundsErrorCode
   140  }
   141  
   142  var _ error = boundsError{}
   143  
   144  // boundsErrorFmts provide error text for various out-of-bounds panics.
   145  // Note: if you change these strings, you should adjust the size of the buffer
   146  // in boundsError.Error below as well.
   147  var boundsErrorFmts = [...]string{
   148  	abi.BoundsIndex:      "index out of range [%x] with length %y",
   149  	abi.BoundsSliceAlen:  "slice bounds out of range [:%x] with length %y",
   150  	abi.BoundsSliceAcap:  "slice bounds out of range [:%x] with capacity %y",
   151  	abi.BoundsSliceB:     "slice bounds out of range [%x:%y]",
   152  	abi.BoundsSlice3Alen: "slice bounds out of range [::%x] with length %y",
   153  	abi.BoundsSlice3Acap: "slice bounds out of range [::%x] with capacity %y",
   154  	abi.BoundsSlice3B:    "slice bounds out of range [:%x:%y]",
   155  	abi.BoundsSlice3C:    "slice bounds out of range [%x:%y:]",
   156  	abi.BoundsConvert:    "cannot convert slice with length %y to array or pointer to array with length %x",
   157  }
   158  
   159  // boundsNegErrorFmts are overriding formats if x is negative. In this case there's no need to report y.
   160  var boundsNegErrorFmts = [...]string{
   161  	abi.BoundsIndex:      "index out of range [%x]",
   162  	abi.BoundsSliceAlen:  "slice bounds out of range [:%x]",
   163  	abi.BoundsSliceAcap:  "slice bounds out of range [:%x]",
   164  	abi.BoundsSliceB:     "slice bounds out of range [%x:]",
   165  	abi.BoundsSlice3Alen: "slice bounds out of range [::%x]",
   166  	abi.BoundsSlice3Acap: "slice bounds out of range [::%x]",
   167  	abi.BoundsSlice3B:    "slice bounds out of range [:%x:]",
   168  	abi.BoundsSlice3C:    "slice bounds out of range [%x::]",
   169  }
   170  
   171  func (e boundsError) RuntimeError() {}
   172  
   173  func appendIntStr(b []byte, v int64, signed bool) []byte {
   174  	if signed && v < 0 {
   175  		b = append(b, '-')
   176  		v = -v
   177  	}
   178  	var buf [20]byte
   179  	b = append(b, itoa(buf[:], uint64(v))...)
   180  	return b
   181  }
   182  
   183  func (e boundsError) Error() string {
   184  	fmt := boundsErrorFmts[e.code]
   185  	if e.signed && e.x < 0 {
   186  		fmt = boundsNegErrorFmts[e.code]
   187  	}
   188  	// max message length is 99: "runtime error: slice bounds out of range [::%x] with capacity %y"
   189  	// x can be at most 20 characters. y can be at most 19.
   190  	b := make([]byte, 0, 100)
   191  	b = append(b, "runtime error: "...)
   192  	for i := 0; i < len(fmt); i++ {
   193  		c := fmt[i]
   194  		if c != '%' {
   195  			b = append(b, c)
   196  			continue
   197  		}
   198  		i++
   199  		switch fmt[i] {
   200  		case 'x':
   201  			b = appendIntStr(b, e.x, e.signed)
   202  		case 'y':
   203  			b = appendIntStr(b, int64(e.y), true)
   204  		}
   205  	}
   206  	return string(b)
   207  }
   208  
   209  type stringer interface {
   210  	String() string
   211  }
   212  
   213  // printpanicval prints an argument passed to panic.
   214  // If panic is called with a value that has a String or Error method,
   215  // it has already been converted into a string by preprintpanics.
   216  //
   217  // To ensure that the traceback can be unambiguously parsed even when
   218  // the panic value contains "\ngoroutine" and other stack-like
   219  // strings, newlines in the string representation of v are replaced by
   220  // "\n\t".
   221  func printpanicval(v any) {
   222  	switch v := v.(type) {
   223  	case nil:
   224  		print("nil")
   225  	case bool:
   226  		print(v)
   227  	case int:
   228  		print(v)
   229  	case int8:
   230  		print(v)
   231  	case int16:
   232  		print(v)
   233  	case int32:
   234  		print(v)
   235  	case int64:
   236  		print(v)
   237  	case uint:
   238  		print(v)
   239  	case uint8:
   240  		print(v)
   241  	case uint16:
   242  		print(v)
   243  	case uint32:
   244  		print(v)
   245  	case uint64:
   246  		print(v)
   247  	case uintptr:
   248  		print(v)
   249  	case float32:
   250  		print(v)
   251  	case float64:
   252  		print(v)
   253  	case complex64:
   254  		print(v)
   255  	case complex128:
   256  		print(v)
   257  	case string:
   258  		printindented(v)
   259  	default:
   260  		printanycustomtype(v)
   261  	}
   262  }
   263  
   264  // Invariant: each newline in the string representation is followed by a tab.
   265  func printanycustomtype(i any) {
   266  	eface := efaceOf(&i)
   267  	typestring := toRType(eface._type).string()
   268  
   269  	switch eface._type.Kind() {
   270  	case abi.String:
   271  		print(typestring, `("`)
   272  		printindented(*(*string)(eface.data))
   273  		print(`")`)
   274  	case abi.Bool:
   275  		print(typestring, "(", *(*bool)(eface.data), ")")
   276  	case abi.Int:
   277  		print(typestring, "(", *(*int)(eface.data), ")")
   278  	case abi.Int8:
   279  		print(typestring, "(", *(*int8)(eface.data), ")")
   280  	case abi.Int16:
   281  		print(typestring, "(", *(*int16)(eface.data), ")")
   282  	case abi.Int32:
   283  		print(typestring, "(", *(*int32)(eface.data), ")")
   284  	case abi.Int64:
   285  		print(typestring, "(", *(*int64)(eface.data), ")")
   286  	case abi.Uint:
   287  		print(typestring, "(", *(*uint)(eface.data), ")")
   288  	case abi.Uint8:
   289  		print(typestring, "(", *(*uint8)(eface.data), ")")
   290  	case abi.Uint16:
   291  		print(typestring, "(", *(*uint16)(eface.data), ")")
   292  	case abi.Uint32:
   293  		print(typestring, "(", *(*uint32)(eface.data), ")")
   294  	case abi.Uint64:
   295  		print(typestring, "(", *(*uint64)(eface.data), ")")
   296  	case abi.Uintptr:
   297  		print(typestring, "(", *(*uintptr)(eface.data), ")")
   298  	case abi.Float32:
   299  		print(typestring, "(", *(*float32)(eface.data), ")")
   300  	case abi.Float64:
   301  		print(typestring, "(", *(*float64)(eface.data), ")")
   302  	case abi.Complex64:
   303  		print(typestring, *(*complex64)(eface.data))
   304  	case abi.Complex128:
   305  		print(typestring, *(*complex128)(eface.data))
   306  	default:
   307  		print("(", typestring, ") ", eface.data)
   308  	}
   309  }
   310  
   311  // printindented prints s, replacing "\n" with "\n\t".
   312  func printindented(s string) {
   313  	for {
   314  		i := bytealg.IndexByteString(s, '\n')
   315  		if i < 0 {
   316  			break
   317  		}
   318  		i += len("\n")
   319  		print(s[:i])
   320  		print("\t")
   321  		s = s[i:]
   322  	}
   323  	print(s)
   324  }
   325  
   326  // panicwrap generates a panic for a call to a wrapped value method
   327  // with a nil pointer receiver.
   328  //
   329  // It is called from the generated wrapper code.
   330  func panicwrap() {
   331  	pc := sys.GetCallerPC()
   332  	name := funcNameForPrint(funcname(findfunc(pc)))
   333  	// name is something like "main.(*T).F".
   334  	// We want to extract pkg ("main"), typ ("T"), and meth ("F").
   335  	// Do it by finding the parens.
   336  	i := bytealg.IndexByteString(name, '(')
   337  	if i < 0 {
   338  		throw("panicwrap: no ( in " + name)
   339  	}
   340  	pkg := name[:i-1]
   341  	if i+2 >= len(name) || name[i-1:i+2] != ".(*" {
   342  		throw("panicwrap: unexpected string after package name: " + name)
   343  	}
   344  	name = name[i+2:]
   345  	i = bytealg.IndexByteString(name, ')')
   346  	if i < 0 {
   347  		throw("panicwrap: no ) in " + name)
   348  	}
   349  	if i+2 >= len(name) || name[i:i+2] != ")." {
   350  		throw("panicwrap: unexpected string after type name: " + name)
   351  	}
   352  	typ := name[:i]
   353  	meth := name[i+2:]
   354  	panic(plainError("value method " + pkg + "." + typ + "." + meth + " called using nil *" + typ + " pointer"))
   355  }
   356  

View as plain text