Source file test/fixedbugs/issue11771.go

     1  // run
     2  
     3  //go:build !nacl && !js && !wasip1 && gc
     4  
     5  // Copyright 2015 The Go Authors. All rights reserved.
     6  // Use of this source code is governed by a BSD-style
     7  // license that can be found in the LICENSE file.
     8  
     9  // Issue 11771: Magic comments should ignore carriage returns.
    10  
    11  package main
    12  
    13  import (
    14  	"bytes"
    15  	"fmt"
    16  	"io/ioutil"
    17  	"log"
    18  	"os"
    19  	"os/exec"
    20  	"path/filepath"
    21  	"runtime"
    22  )
    23  
    24  func main() {
    25  	if runtime.Compiler != "gc" {
    26  		return
    27  	}
    28  
    29  	dir, err := ioutil.TempDir("", "go-issue11771")
    30  	if err != nil {
    31  		log.Fatalf("creating temp dir: %v\n", err)
    32  	}
    33  	defer os.RemoveAll(dir)
    34  
    35  	// The go:nowritebarrier magic comment is only permitted in
    36  	// the runtime package.  So we confirm that the compilation
    37  	// fails.
    38  
    39  	var buf bytes.Buffer
    40  	fmt.Fprintln(&buf, `
    41  package main
    42  
    43  func main() {
    44  }
    45  `)
    46  	fmt.Fprintln(&buf, "//go:nowritebarrier\r")
    47  	fmt.Fprintln(&buf, `
    48  func x() {
    49  }
    50  `)
    51  
    52  	if err := ioutil.WriteFile(filepath.Join(dir, "x.go"), buf.Bytes(), 0666); err != nil {
    53  		log.Fatal(err)
    54  	}
    55  
    56  	cmd := exec.Command("go", "tool", "compile", "-p=p", "x.go")
    57  	cmd.Dir = dir
    58  	output, err := cmd.CombinedOutput()
    59  	if err == nil {
    60  		log.Fatal("compile succeeded unexpectedly")
    61  	}
    62  	if !bytes.Contains(output, []byte("only allowed in runtime")) {
    63  		log.Fatalf("wrong error message from compiler; got:\n%s\n", output)
    64  	}
    65  }
    66  

View as plain text