blob: 6304ce073aa9e558dbc884b2d71a382e600f2ebd [file] [log] [blame]
Colin Cross7bb052a2015-02-03 12:59:37 -08001// run
2
Dan Willemsen0c157092016-07-08 13:57:52 -07003// Copyright 2013 The Go Authors. All rights reserved.
Colin Cross7bb052a2015-02-03 12:59:37 -08004// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file.
6
7package main
8
9import (
10 "strings"
11 "unsafe"
12)
13
14type T []int
15
16func main() {
17 n := -1
Dan Willemsenbbdf6642017-01-13 22:57:23 -080018 shouldPanic("len out of range", func() { _ = make(T, n) })
19 shouldPanic("cap out of range", func() { _ = make(T, 0, n) })
20 shouldPanic("len out of range", func() { _ = make(T, int64(n)) })
21 shouldPanic("cap out of range", func() { _ = make(T, 0, int64(n)) })
Colin Cross7bb052a2015-02-03 12:59:37 -080022 var t *byte
23 if unsafe.Sizeof(t) == 8 {
Colin Cross1371fe42019-03-19 21:08:48 -070024 // Test mem > maxAlloc
25 var n2 int64 = 1 << 59
Dan Willemsenf3f2eb62018-08-28 11:28:58 -070026 shouldPanic("len out of range", func() { _ = make(T, int(n2)) })
27 shouldPanic("cap out of range", func() { _ = make(T, 0, int(n2)) })
Colin Cross1371fe42019-03-19 21:08:48 -070028 // Test elem.size*cap overflow
Dan Willemsenf3f2eb62018-08-28 11:28:58 -070029 n2 = 1<<63 - 1
30 shouldPanic("len out of range", func() { _ = make(T, int(n2)) })
31 shouldPanic("cap out of range", func() { _ = make(T, 0, int(n2)) })
Colin Cross7bb052a2015-02-03 12:59:37 -080032 } else {
33 n = 1<<31 - 1
Dan Willemsenbbdf6642017-01-13 22:57:23 -080034 shouldPanic("len out of range", func() { _ = make(T, n) })
35 shouldPanic("cap out of range", func() { _ = make(T, 0, n) })
36 shouldPanic("len out of range", func() { _ = make(T, int64(n)) })
37 shouldPanic("cap out of range", func() { _ = make(T, 0, int64(n)) })
Colin Cross7bb052a2015-02-03 12:59:37 -080038 }
Dan Willemsenf3f2eb62018-08-28 11:28:58 -070039
40 // Test make in append panics since the gc compiler optimizes makes in appends.
41 shouldPanic("len out of range", func() { _ = append(T{}, make(T, n)...) })
42 shouldPanic("cap out of range", func() { _ = append(T{}, make(T, 0, n)...) })
43 shouldPanic("len out of range", func() { _ = append(T{}, make(T, int64(n))...) })
44 shouldPanic("cap out of range", func() { _ = append(T{}, make(T, 0, int64(n))...) })
Colin Cross7bb052a2015-02-03 12:59:37 -080045}
46
47func shouldPanic(str string, f func()) {
48 defer func() {
49 err := recover()
50 if err == nil {
51 panic("did not panic")
52 }
53 s := err.(error).Error()
54 if !strings.Contains(s, str) {
55 panic("got panic " + s + ", want " + str)
56 }
57 }()
Dan Willemsenbbdf6642017-01-13 22:57:23 -080058
Colin Cross7bb052a2015-02-03 12:59:37 -080059 f()
60}