const_xor_width.mx raw

   1  // ^ on a sized unsigned constant keeps that width, through a conversion.
   2  //
   3  // The defect this pins: the typed-constant path masked ^x to the operand's
   4  // width, but the SSA fold that runs first returned the raw all-ones, so
   5  // int32(^uint8(0)) was -1 and int32(^uint16(0)) was -1. It only shows THROUGH a
   6  // conversion: assigned to a sized variable the value truncates back to the right
   7  // bits, which is why the bug hid everywhere except dnsmessage's
   8  // `conLen > int32(^uint16(0))` - a comparison that was always true.
   9  //
  10  // All four widths are asserted through a conversion, plus the signed controls
  11  // and the variable form (which was always correct).
  12  package main
  13  
  14  import (
  15  	"fmt"
  16  	"os"
  17  )
  18  
  19  // want asserts one width and reports whether it held. The counter lives in main
  20  // as a local: a package global cannot be mutated outside init here.
  21  func want(label string, got int64, exp int64) (ok bool) {
  22  	if got != exp {
  23  		fmt.Printf("FAIL %-22s got %d want %d\n", label, got, exp)
  24  		return false
  25  	}
  26  	fmt.Printf("ok   %-22s %d\n", label, got)
  27  	return true
  28  }
  29  
  30  func main() {
  31  	// Termination: a batch program must still be stoppable, so the entry
  32  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  33  	select {
  34  	case <-shutdown:
  35  		return
  36  	default:
  37  	}
  38  
  39  	var fails int32
  40  	if !want("int32(^uint8(0))", int64(int32(^uint8(0))), 255) {
  41  		fails = fails + 1
  42  	}
  43  	if !want("int32(^uint16(0))", int64(int32(^uint16(0))), 65535) {
  44  		fails = fails + 1
  45  	}
  46  	if !want("int64(^uint32(0))", int64(^uint32(0)), 4294967295) {
  47  		fails = fails + 1
  48  	}
  49  	// uint64 through a conversion: the value does not fit int64, so compare its
  50  	// high half through a shift instead of a signed conversion.
  51  	if !want("uint64(^uint64(0))>>32", int64((^uint64(0))>>32), 4294967295) {
  52  		fails = fails + 1
  53  	}
  54  	if !want("int32(^int8(0))", int64(int32(^int8(0))), -1) {
  55  		fails = fails + 1
  56  	}
  57  	if !want("int32(^int16(0))", int64(int32(^int16(0))), -1) {
  58  		fails = fails + 1
  59  	}
  60  	var z8 uint8
  61  	var z16 uint16
  62  	if !want("int32(^z8)", int64(int32(^z8)), 255) {
  63  		fails = fails + 1
  64  	}
  65  	if !want("int32(^z16)", int64(int32(^z16)), 65535) {
  66  		fails = fails + 1
  67  	}
  68  
  69  	if fails != 0 {
  70  		fmt.Printf("const_xor_width: %d wrong\n", fails)
  71  		os.Exit(1)
  72  	}
  73  	fmt.Printf("const_xor_width ok\n")
  74  }
  75