[dev.link] all: merge branch 'master' into dev.link

Change-Id: I644cfc9dfd6e024a0d62bbd226db8639e4a87dc7
This commit is contained in:
Cherry Zhang 2020-07-10 14:54:13 -04:00
commit 86f53c2a3c
67 changed files with 1172 additions and 642 deletions

View file

@ -563,6 +563,7 @@ Hitoshi Mitake <mitake.hitoshi@gmail.com>
Holden Huang <ttyh061@gmail.com> Holden Huang <ttyh061@gmail.com>
Hong Ruiqi <hongruiqi@gmail.com> Hong Ruiqi <hongruiqi@gmail.com>
Hongfei Tan <feilengcui008@gmail.com> Hongfei Tan <feilengcui008@gmail.com>
Hootsuite Inc.
Hsin-Ho Yeh <yhh92u@gmail.com> Hsin-Ho Yeh <yhh92u@gmail.com>
Hu Keping <hukeping@huawei.com> Hu Keping <hukeping@huawei.com>
Hugues Bruant <hugues.bruant@gmail.com> Hugues Bruant <hugues.bruant@gmail.com>

View file

@ -1303,6 +1303,7 @@ Kshitij Saraogi <kshitijsaraogi@gmail.com>
Kun Li <likunarmstrong@gmail.com> Kun Li <likunarmstrong@gmail.com>
Kunpei Sakai <namusyaka@gmail.com> Kunpei Sakai <namusyaka@gmail.com>
Kuntal Majumder <hellozee@disroot.org> Kuntal Majumder <hellozee@disroot.org>
Kush Patel <kush.patel@hootsuite.com>
Kyle Consalus <consalus@gmail.com> Kyle Consalus <consalus@gmail.com>
Kyle Isom <kyle@gokyle.net> Kyle Isom <kyle@gokyle.net>
Kyle Jones <kyle@kyledj.com> Kyle Jones <kyle@kyledj.com>

View file

@ -174,7 +174,7 @@ The main Go repository is located at
a Git server hosted by Google. a Git server hosted by Google.
Authentication on the web server is made through your Google account, but Authentication on the web server is made through your Google account, but
you also need to configure <code>git</code> on your computer to access it. you also need to configure <code>git</code> on your computer to access it.
Follow this steps: Follow these steps:
</p> </p>
<ol> <ol>
@ -310,7 +310,7 @@ Most issues will be marked with one of the following workflow labels:
<b>NeedsDecision</b>: the issue is relatively well understood, but the <b>NeedsDecision</b>: the issue is relatively well understood, but the
Go team hasn't yet decided the best way to address it. Go team hasn't yet decided the best way to address it.
It would be better to wait for a decision before writing code. It would be better to wait for a decision before writing code.
If you are interested on working on an issue in this state, If you are interested in working on an issue in this state,
feel free to "ping" maintainers in the issue's comments feel free to "ping" maintainers in the issue's comments
if some time has passed without a decision. if some time has passed without a decision.
</li> </li>

View file

@ -20,7 +20,7 @@ editing, navigation, testing, and debugging experience.
<ul> <ul>
<li><a href="https://github.com/fatih/vim-go">vim</a>: vim-go plugin provides Go programming language support</li> <li><a href="https://github.com/fatih/vim-go">vim</a>: vim-go plugin provides Go programming language support</li>
<li><a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.Go">Visual Studio Code</a>: <li><a href="https://marketplace.visualstudio.com/items?itemName=golang.go">Visual Studio Code</a>:
Go extension provides support for the Go programming language</li> Go extension provides support for the Go programming language</li>
<li><a href="https://www.jetbrains.com/go">GoLand</a>: GoLand is distributed either as a standalone IDE <li><a href="https://www.jetbrains.com/go">GoLand</a>: GoLand is distributed either as a standalone IDE
or as a plugin for IntelliJ IDEA Ultimate</li> or as a plugin for IntelliJ IDEA Ultimate</li>

View file

@ -2336,10 +2336,9 @@ of the request from the client.
</p> </p>
<p> <p>
For brevity, let's ignore POSTs and assume HTTP requests are always For brevity, let's ignore POSTs and assume HTTP requests are always
GETs; that simplification does not affect the way the handlers are GETs; that simplification does not affect the way the handlers are set up.
set up. Here's a trivial but complete implementation of a handler to Here's a trivial implementation of a handler to count the number of times
count the number of times the the page is visited.
page is visited.
</p> </p>
<pre> <pre>
// Simple counter server. // Simple counter server.
@ -2355,6 +2354,11 @@ func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
<p> <p>
(Keeping with our theme, note how <code>Fprintf</code> can print to an (Keeping with our theme, note how <code>Fprintf</code> can print to an
<code>http.ResponseWriter</code>.) <code>http.ResponseWriter</code>.)
In a real server, access to <code>ctr.n</code> would need protection from
concurrent access.
See the <code>sync</code> and <code>atomic</code> packages for suggestions.
</p>
<p>
For reference, here's how to attach such a server to a node on the URL tree. For reference, here's how to attach such a server to a node on the URL tree.
</p> </p>
<pre> <pre>

View file

@ -34,9 +34,9 @@ Do not send CLs removing the interior tags from such phrases.
<h3 id="darwin">Darwin</h3> <h3 id="darwin">Darwin</h3>
<p> <p>
As <a href="go1.14#darwin">announced</a> in the Go 1.14 release notes, As <a href="go1.14#darwin">announced</a> in the Go 1.14 release
Go 1.15 now requires macOS 10.12 Sierra or later; notes, Go 1.15 requires macOS 10.12 Sierra or later; support for
support for previous versions has been discontinued. previous versions has been discontinued.
</p> </p>
<p> <!-- golang.org/issue/37610, golang.org/issue/37611, CL 227582, and CL 227198 --> <p> <!-- golang.org/issue/37610, golang.org/issue/37611, CL 227582, and CL 227198 -->
@ -50,9 +50,9 @@ Do not send CLs removing the interior tags from such phrases.
<h3 id="windows">Windows</h3> <h3 id="windows">Windows</h3>
<p> <!-- CL 214397 and CL 230217 --> <p> <!-- CL 214397 and CL 230217 -->
Go 1.15 now generates Windows ASLR executables when <code>-buildmode=pie</code> Go now generates Windows ASLR executables when <code>-buildmode=pie</code>
cmd/link flag is provided. Go command uses <code>-buildmode=pie</code> by default cmd/link flag is provided. Go command uses <code>-buildmode=pie</code>
on Windows. by default on Windows.
</p> </p>
<p><!-- CL 227003 --> <p><!-- CL 227003 -->
@ -177,7 +177,8 @@ Do not send CLs removing the interior tags from such phrases.
</p> </p>
<p> <p>
This new vet check is enabled by default when using <code>go test</code>. This new vet check is enabled by default when
using <code>go</code> <code>test</code>.
</p> </p>
<p> <p>
@ -205,7 +206,8 @@ Do not send CLs removing the interior tags from such phrases.
</p> </p>
<p> <p>
This new vet check is enabled by default when using <code>go test</code>. This new vet check is enabled by default when
using <code>go</code> <code>test</code>.
</p> </p>
<p> <p>
@ -333,6 +335,13 @@ Do not send CLs removing the interior tags from such phrases.
improvements expected in future releases. improvements expected in future releases.
</p> </p>
<p><!-- CL 207877 -->
The linker now defaults to internal linking mode
for <code>-buildmode=pie</code> on
<code>linux/amd64</code> and <code>linux/arm64</code>, so these
configurations no longer require a C linker.
</p>
<h2 id="objdump">Objdump</h2> <h2 id="objdump">Objdump</h2>
<p><!-- CL 225459 --> <p><!-- CL 225459 -->
@ -447,7 +456,7 @@ Do not send CLs removing the interior tags from such phrases.
<a href="/pkg/crypto/tls/#Dialer"><code>Dialer</code></a> <a href="/pkg/crypto/tls/#Dialer"><code>Dialer</code></a>
type and its type and its
<a href="/pkg/crypto/tls/#Dialer.DialContext"><code>DialContext</code></a> <a href="/pkg/crypto/tls/#Dialer.DialContext"><code>DialContext</code></a>
method permits using a context to both connect and handshake with a TLS server. method permit using a context to both connect and handshake with a TLS server.
</p> </p>
<p><!-- CL 229122 --> <p><!-- CL 229122 -->
@ -546,11 +555,11 @@ Do not send CLs removing the interior tags from such phrases.
<dl id="crypto/x509/pkix"><dt><a href="/pkg/crypto/x509/pkix/">crypto/x509/pkix</a></dt> <dl id="crypto/x509/pkix"><dt><a href="/pkg/crypto/x509/pkix/">crypto/x509/pkix</a></dt>
<dd> <dd>
<p><!-- CL 229864 --> <p><!-- CL 229864, CL 240543 -->
<a href="/pkg/crypto/x509/pkix/#Name.String"><code>Name.String</code></a> <a href="/pkg/crypto/x509/pkix/#Name.String"><code>Name.String</code></a>
now prints non-standard attributes from now prints non-standard attributes from
<a href="/pkg/crypto/x509/pkix/#Name.Names"><code>Names</code></a> if <a href="/pkg/crypto/x509/pkix/#Name.Names"><code>Names</code></a> if
<a href="/pkg/crypto/x509/pkix/#Name.ExtraNames"><code>ExtraNames</code></a> is empty. <a href="/pkg/crypto/x509/pkix/#Name.ExtraNames"><code>ExtraNames</code></a> is nil.
</p> </p>
</dd> </dd>
</dl><!-- crypto/x509/pkix --> </dl><!-- crypto/x509/pkix -->
@ -595,6 +604,20 @@ Do not send CLs removing the interior tags from such phrases.
</dd> </dd>
</dl><!-- debug/pe --> </dl><!-- debug/pe -->
<dl id="encoding/asn1"><dt><a href="/pkg/encoding/asn1/">encoding/asn1</a></dt>
<dd>
<p><!-- CL 226984 -->
<a href="/pkg/encoding/asn1/#Marshal"><code>Marshal</code></a> now sorts the components
of SET OF according to X.690 DER.
</p>
<p><!-- CL 227320 -->
<a href="/pkg/encoding/asn1/#Unmarshal"><code>Unmarshal</code></a> now rejects tags and
Object Identifiers which are not minimally encoded according to X.690 DER.
</p>
</dd>
</dl><!-- encoding/asn1 -->
<dl id="encoding/json"><dt><a href="/pkg/encoding/json/">encoding/json</a></dt> <dl id="encoding/json"><dt><a href="/pkg/encoding/json/">encoding/json</a></dt>
<dd> <dd>
<p><!-- CL 191783 --> <p><!-- CL 191783 -->
@ -603,32 +626,19 @@ Do not send CLs removing the interior tags from such phrases.
</p> </p>
<p><!-- CL 199837 --> <p><!-- CL 199837 -->
Introduce an internal limit to the maximum depth of nesting when decoding. The package now has an internal limit to the maximum depth of
This reduces the possibility that a deeply nested input could use large quantities nesting when decoding. This reduces the possibility that a
of stack memory, or even cause a "goroutine stack exceeds limit" panic. deeply nested input could use large quantities of stack memory,
or even cause a "goroutine stack exceeds limit" panic.
</p> </p>
</dd> </dd>
</dl><!-- encoding/json --> </dl><!-- encoding/json -->
<dl id="encoding/xml"><dt><a href="/pkg/encoding/xml/">encoding/xml</a></dt>
<dd>
<p><!-- CL 203417 -->
The encoder has always taken care to avoid using namespace prefixes beginning with
<code>xml</code>,
which are reserved by the XML specification.
Now, following the specification more closely,
that check is case-insensitive, so that prefixes beginning with
<code>XML</code>, <code>XmL</code>,
and so on are also avoided.
</p>
</dd>
</dl><!-- encoding/xml -->
<dl id="flag"><dt><a href="/pkg/flag/">flag</a></dt> <dl id="flag"><dt><a href="/pkg/flag/">flag</a></dt>
<dd> <dd>
<p><!-- CL 221427 --> <p><!-- CL 221427 -->
When the flag package sees <code>-h</code> or <code>-help</code>, and When the flag package sees <code>-h</code> or <code>-help</code>, and
those flags are not defined, the flag package prints a usage message. those flags are not defined, it now prints a usage message.
If the <a href="/pkg/flag/#FlagSet"><code>FlagSet</code></a> was created with If the <a href="/pkg/flag/#FlagSet"><code>FlagSet</code></a> was created with
<a href="/pkg/flag/#ExitOnError"><code>ExitOnError</code></a>, <a href="/pkg/flag/#ExitOnError"><code>ExitOnError</code></a>,
<a href="/pkg/flag/#FlagSet.Parse"><code>FlagSet.Parse</code></a> would then <a href="/pkg/flag/#FlagSet.Parse"><code>FlagSet.Parse</code></a> would then
@ -658,6 +668,17 @@ Do not send CLs removing the interior tags from such phrases.
</dd> </dd>
</dl><!-- go/printer --> </dl><!-- go/printer -->
<dl id="html/template"><dt><a href="/pkg/html/template/">html/template</a></dt>
<dd>
<p><!-- CL 226097 -->
The package now uses Unicode escapes (<code>\uNNNN</code>) in all
JavaScript and JSON contexts. This fixes escaping errors in
<code>application/ld+json</code> and <code>application/json</code>
contexts.
</p>
</dd>
</dl><!-- html/template -->
<dl id="io/ioutil"><dt><a href="/pkg/io/ioutil/">io/ioutil</a></dt> <dl id="io/ioutil"><dt><a href="/pkg/io/ioutil/">io/ioutil</a></dt>
<dd> <dd>
<p><!-- CL 212597 --> <p><!-- CL 212597 -->
@ -931,13 +952,28 @@ Do not send CLs removing the interior tags from such phrases.
<p><!-- CL 226877, golang.org/issue/35998 --> <p><!-- CL 226877, golang.org/issue/35998 -->
The new methods The new methods
<a href="/pkg/testing/#T.TempDir"><code>T.TempDir</code></a> and <a href="/pkg/testing/#T.TempDir"><code>T.TempDir</code></a> and
<a href="/pkg/testing/#B.TempDir"><code>B.TempDir</code></a> and <a href="/pkg/testing/#B.TempDir"><code>B.TempDir</code></a>
return temporary directories that are automatically cleaned up return temporary directories that are automatically cleaned up
at the end of the test. at the end of the test.
</p> </p>
<p><!-- CL 229085 -->
<code>go</code> <code>test</code> <code>-v</code> now groups output by
test name, rather than printing the test name on each line.
</p>
</dd> </dd>
</dl><!-- testing --> </dl><!-- testing -->
<dl id="text/template"><dt><a href="/pkg/text/template/">text/template</a></dt>
<dd>
<p><!-- CL 226097 -->
<a href="/pkg/text/template/#JSEscape"><code>JSEscape</code></a> now
consistently uses Unicode escapes (<code>\u00XX</code>), which are
compatible with JSON.
</p>
</dd>
</dl><!-- text/template -->
<dl id="time"><dt><a href="/pkg/time/">time</a></dt> <dl id="time"><dt><a href="/pkg/time/">time</a></dt>
<dd> <dd>
<p><!-- CL 220424, CL 217362, golang.org/issue/33184 --> <p><!-- CL 220424, CL 217362, golang.org/issue/33184 -->

View file

@ -8,7 +8,7 @@
<h2 id="help">Get help</h2> <h2 id="help">Get help</h2>
<img class="gopher" src="/doc/gopher/help.png"/> <img class="gopher" src="/doc/gopher/help.png" alt=""/>
{{if not $.GoogleCN}} {{if not $.GoogleCN}}
<h3 id="mailinglist"><a href="https://groups.google.com/group/golang-nuts">Go Nuts Mailing List</a></h3> <h3 id="mailinglist"><a href="https://groups.google.com/group/golang-nuts">Go Nuts Mailing List</a></h3>

View file

@ -33,7 +33,7 @@ compiler using the GCC back end, see
</p> </p>
<p> <p>
The Go compilers support twelve instruction sets: The Go compilers support the following instruction sets:
<dl> <dl>
<dt> <dt>
@ -48,24 +48,30 @@ The Go compilers support twelve instruction sets:
<dd> <dd>
The <code>ARM</code> instruction set, 64-bit (<code>AArch64</code>) and 32-bit. The <code>ARM</code> instruction set, 64-bit (<code>AArch64</code>) and 32-bit.
</dd> </dd>
<dt>
<code>mips64</code>, <code>mips64le</code>, <code>mips</code>, <code>mipsle</code>
</dt>
<dd>
The <code>MIPS</code> instruction set, big- and little-endian, 64- and 32-bit.
</dd>
<dt> <dt>
<code>ppc64</code>, <code>ppc64le</code> <code>ppc64</code>, <code>ppc64le</code>
</dt> </dt>
<dd> <dd>
The 64-bit PowerPC instruction set, big- and little-endian. The 64-bit PowerPC instruction set, big- and little-endian.
</dd> </dd>
<dt>
<code>riscv64</code>
</dt>
<dd>
The 64-bit RISC-V instruction set.
</dd>
<dt> <dt>
<code>s390x</code> <code>s390x</code>
</dt> </dt>
<dd> <dd>
The IBM z/Architecture. The IBM z/Architecture.
</dd> </dd>
<dt>
<code>mips64</code>, <code>mips64le</code>, <code>mips</code>, <code>mipsle</code>
</dt>
<dd>
The <code>MIPS</code> instruction set, big- and little-endian, 64- and 32-bit.
</dd>
<dt> <dt>
<code>wasm</code> <code>wasm</code>
</dt> </dt>

View file

@ -2200,3 +2200,7 @@ func test32579(t *testing.T) {
// issue 38649 // issue 38649
var issue38649 C.netbsd_gid = 42 var issue38649 C.netbsd_gid = 42
// issue 39877
var issue39877 *C.void = nil

View file

@ -38,7 +38,15 @@ var testWork = flag.Bool("testwork", false, "if true, log and do not delete the
// run runs a command and calls t.Errorf if it fails. // run runs a command and calls t.Errorf if it fails.
func run(t *testing.T, msg string, args ...string) { func run(t *testing.T, msg string, args ...string) {
runWithEnv(t, msg, nil, args...)
}
// runWithEnv runs a command under the given environment and calls t.Errorf if it fails.
func runWithEnv(t *testing.T, msg string, env []string, args ...string) {
c := exec.Command(args[0], args[1:]...) c := exec.Command(args[0], args[1:]...)
if len(env) != 0 {
c.Env = append(os.Environ(), env...)
}
if output, err := c.CombinedOutput(); err != nil { if output, err := c.CombinedOutput(); err != nil {
t.Errorf("executing %s (%s) failed %s:\n%s", strings.Join(args, " "), msg, err, output) t.Errorf("executing %s (%s) failed %s:\n%s", strings.Join(args, " "), msg, err, output)
} }
@ -1034,3 +1042,11 @@ func TestGeneratedHash(t *testing.T) {
func TestPackageOrder(t *testing.T) { func TestPackageOrder(t *testing.T) {
goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue39777/a", "./issue39777/b") goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue39777/a", "./issue39777/b")
} }
// Test that GC data are generated correctly by the linker when it needs a type defined in
// a shared library. See issue 39927.
func TestGCData(t *testing.T) {
goCmd(t, "install", "-buildmode=shared", "-linkshared", "./gcdata/p")
goCmd(t, "build", "-linkshared", "./gcdata/main")
runWithEnv(t, "running gcdata/main", []string{"GODEBUG=clobberfree=1"}, "./main")
}

View file

@ -0,0 +1,37 @@
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test that GC data is generated correctly for global
// variables with types defined in a shared library.
// See issue 39927.
// This test run under GODEBUG=clobberfree=1. The check
// *x[i] == 12345 depends on this debug mode to clobber
// the value if the object is freed prematurely.
package main
import (
"fmt"
"runtime"
"testshared/gcdata/p"
)
var x p.T
func main() {
for i := range x {
x[i] = new(int)
*x[i] = 12345
}
runtime.GC()
runtime.GC()
runtime.GC()
for i := range x {
if *x[i] != 12345 {
fmt.Printf("x[%d] == %d, want 12345\n", i, *x[i])
panic("FAIL")
}
}
}

View file

@ -0,0 +1,7 @@
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package p
type T [10]*int

View file

@ -98,6 +98,11 @@ func (p *Package) writeDefs() {
typedefNames := make([]string, 0, len(typedef)) typedefNames := make([]string, 0, len(typedef))
for name := range typedef { for name := range typedef {
if name == "_Ctype_void" {
// We provide an appropriate declaration for
// _Ctype_void below (#39877).
continue
}
typedefNames = append(typedefNames, name) typedefNames = append(typedefNames, name)
} }
sort.Strings(typedefNames) sort.Strings(typedefNames)

View file

@ -6,7 +6,7 @@ require (
github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3 github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3
github.com/ianlancetaylor/demangle v0.0.0-20200414190113-039b1ae3a340 // indirect github.com/ianlancetaylor/demangle v0.0.0-20200414190113-039b1ae3a340 // indirect
golang.org/x/arch v0.0.0-20200511175325-f7c78586839d golang.org/x/arch v0.0.0-20200511175325-f7c78586839d
golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79 golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
golang.org/x/mod v0.3.0 golang.org/x/mod v0.3.0
golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3 // indirect golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3 // indirect
golang.org/x/tools v0.0.0-20200616133436-c1934b75d054 golang.org/x/tools v0.0.0-20200616133436-c1934b75d054

View file

@ -11,8 +11,8 @@ golang.org/x/arch v0.0.0-20200511175325-f7c78586839d h1:YvwchuJby5xEAPdBGmdAVSiV
golang.org/x/arch v0.0.0-20200511175325-f7c78586839d/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4= golang.org/x/arch v0.0.0-20200511175325-f7c78586839d/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79 h1:IaQbIIB2X/Mp/DKctl6ROxz1KyMlKp4uyvL6+kQ7C88= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=

View file

@ -487,6 +487,8 @@ var (
pkgArgs []string pkgArgs []string
pkgs []*load.Package pkgs []*load.Package
testHelp bool // -help option passed to test via -args
testKillTimeout = 100 * 365 * 24 * time.Hour // backup alarm; defaults to about a century if no timeout is set testKillTimeout = 100 * 365 * 24 * time.Hour // backup alarm; defaults to about a century if no timeout is set
testCacheExpire time.Time // ignore cached test results before this time testCacheExpire time.Time // ignore cached test results before this time
@ -532,7 +534,7 @@ func testNeedBinary() bool {
// testShowPass reports whether the output for a passing test should be shown. // testShowPass reports whether the output for a passing test should be shown.
func testShowPass() bool { func testShowPass() bool {
return testV || (testList != "") return testV || (testList != "") || testHelp
} }
var defaultVetFlags = []string{ var defaultVetFlags = []string{

View file

@ -333,6 +333,23 @@ func testFlags(args []string) (packageNames, passToTest []string) {
injectedFlags = append(injectedFlags, "-test.outputdir="+testOutputDir) injectedFlags = append(injectedFlags, "-test.outputdir="+testOutputDir)
} }
// If the user is explicitly passing -help or -h, show output
// of the test binary so that the help output is displayed
// even though the test will exit with success.
// This loop is imperfect: it will do the wrong thing for a case
// like -args -test.outputdir -help. Such cases are probably rare,
// and getting this wrong doesn't do too much harm.
helpLoop:
for _, arg := range explicitArgs {
switch arg {
case "--":
break helpLoop
case "-h", "-help", "--help":
testHelp = true
break helpLoop
}
}
// Ensure that -race and -covermode are compatible. // Ensure that -race and -covermode are compatible.
if testCoverMode == "" { if testCoverMode == "" {
testCoverMode = "set" testCoverMode = "set"

View file

@ -57,6 +57,10 @@ stderr -count=1 'invalid value "walrus" for flag -covermode: valid modes are .*$
stderr '^usage: go test .*$' stderr '^usage: go test .*$'
stderr '^Run ''go help test'' and ''go help testflag'' for details.$' stderr '^Run ''go help test'' and ''go help testflag'' for details.$'
# Passing -help to the test binary should show flag help.
go test ./x -args -help
stdout 'usage_message'
# -covermode, -coverpkg, and -coverprofile should imply -cover # -covermode, -coverpkg, and -coverprofile should imply -cover
go test -covermode=set ./x go test -covermode=set ./x
stdout '\s+coverage:\s+' stdout '\s+coverage:\s+'
@ -98,6 +102,8 @@ import (
"testing" "testing"
) )
var _ = flag.String("usage_message", "", "dummy flag to check usage message")
func TestLogTimeout(t *testing.T) { func TestLogTimeout(t *testing.T) {
t.Log(flag.Lookup("test.timeout").Value) t.Log(flag.Lookup("test.timeout").Value)
} }

View file

@ -10,6 +10,7 @@ import (
"cmd/link/internal/loader" "cmd/link/internal/loader"
"cmd/link/internal/sym" "cmd/link/internal/sym"
"debug/elf" "debug/elf"
"log"
) )
// Decoding the type.* symbols. This has to be in sync with // Decoding the type.* symbols. This has to be in sync with
@ -225,8 +226,15 @@ func decodetypeGcmask(ctxt *Link, s loader.Sym) []byte {
ptrdata := decodetypePtrdata(ctxt.Arch, symData) ptrdata := decodetypePtrdata(ctxt.Arch, symData)
sect := findShlibSection(ctxt, ctxt.loader.SymPkg(s), addr) sect := findShlibSection(ctxt, ctxt.loader.SymPkg(s), addr)
if sect != nil { if sect != nil {
r := make([]byte, ptrdata/int64(ctxt.Arch.PtrSize)) bits := ptrdata / int64(ctxt.Arch.PtrSize)
sect.ReadAt(r, int64(addr-sect.Addr)) r := make([]byte, (bits+7)/8)
// ldshlibsyms avoids closing the ELF file so sect.ReadAt works.
// If we remove this read (and the ones in decodetypeGcprog), we
// can close the file.
_, err := sect.ReadAt(r, int64(addr-sect.Addr))
if err != nil {
log.Fatal(err)
}
return r return r
} }
Exitf("cannot find gcmask for %s", ctxt.loader.SymName(s)) Exitf("cannot find gcmask for %s", ctxt.loader.SymName(s))
@ -247,9 +255,15 @@ func decodetypeGcprog(ctxt *Link, s loader.Sym) []byte {
// A gcprog is a 4-byte uint32 indicating length, followed by // A gcprog is a 4-byte uint32 indicating length, followed by
// the actual program. // the actual program.
progsize := make([]byte, 4) progsize := make([]byte, 4)
sect.ReadAt(progsize, int64(addr-sect.Addr)) _, err := sect.ReadAt(progsize, int64(addr-sect.Addr))
if err != nil {
log.Fatal(err)
}
progbytes := make([]byte, ctxt.Arch.ByteOrder.Uint32(progsize)) progbytes := make([]byte, ctxt.Arch.ByteOrder.Uint32(progsize))
sect.ReadAt(progbytes, int64(addr-sect.Addr+4)) _, err = sect.ReadAt(progbytes, int64(addr-sect.Addr+4))
if err != nil {
log.Fatal(err)
}
return append(progsize, progbytes...) return append(progsize, progbytes...)
} }
Exitf("cannot find gcmask for %s", ctxt.loader.SymName(s)) Exitf("cannot find gcmask for %s", ctxt.loader.SymName(s))
@ -264,7 +278,7 @@ func decodetypeGcprog(ctxt *Link, s loader.Sym) []byte {
func findShlibSection(ctxt *Link, path string, addr uint64) *elf.Section { func findShlibSection(ctxt *Link, path string, addr uint64) *elf.Section {
for _, shlib := range ctxt.Shlibs { for _, shlib := range ctxt.Shlibs {
if shlib.Path == path { if shlib.Path == path {
for _, sect := range shlib.File.Sections { for _, sect := range shlib.File.Sections[1:] { // skip the NULL section
if sect.Addr <= addr && addr <= sect.Addr+sect.Size { if sect.Addr <= addr && addr <= sect.Addr+sect.Size {
return sect return sect
} }
@ -275,8 +289,5 @@ func findShlibSection(ctxt *Link, path string, addr uint64) *elf.Section {
} }
func decodetypeGcprogShlib(ctxt *Link, data []byte) uint64 { func decodetypeGcprogShlib(ctxt *Link, data []byte) uint64 {
if ctxt.Arch.Family == sys.ARM64 {
return 0
}
return decodeInuxi(ctxt.Arch, data[2*int32(ctxt.Arch.PtrSize)+8+1*int32(ctxt.Arch.PtrSize):], ctxt.Arch.PtrSize) return decodeInuxi(ctxt.Arch, data[2*int32(ctxt.Arch.PtrSize)+8+1*int32(ctxt.Arch.PtrSize):], ctxt.Arch.PtrSize)
} }

View file

@ -28,6 +28,21 @@ func TestFallocate(t *testing.T) {
} }
defer out.Close() defer out.Close()
// Try fallocate first.
for {
err = out.fallocate(1 << 10)
if err == syscall.EOPNOTSUPP { // The underlying file system may not support fallocate
t.Skip("fallocate is not supported")
}
if err == syscall.EINTR {
continue // try again
}
if err != nil {
t.Fatalf("fallocate failed: %v", err)
}
break
}
// Mmap 1 MiB initially, and grow to 2 and 3 MiB. // Mmap 1 MiB initially, and grow to 2 and 3 MiB.
// Check if the file size and disk usage is expected. // Check if the file size and disk usage is expected.
for _, sz := range []int64{1 << 20, 2 << 20, 3 << 20} { for _, sz := range []int64{1 << 20, 2 << 20, 3 << 20} {

View file

@ -123,12 +123,14 @@ type ArchSyms struct {
// mkArchSym is a helper for setArchSyms, to set up a special symbol. // mkArchSym is a helper for setArchSyms, to set up a special symbol.
func (ctxt *Link) mkArchSym(name string, ver int, ls *loader.Sym) { func (ctxt *Link) mkArchSym(name string, ver int, ls *loader.Sym) {
*ls = ctxt.loader.LookupOrCreateSym(name, ver) *ls = ctxt.loader.LookupOrCreateSym(name, ver)
ctxt.loader.SetAttrReachable(*ls, true)
} }
// mkArchVecSym is similar to setArchSyms, but operates on elements within // mkArchVecSym is similar to setArchSyms, but operates on elements within
// a slice, where each element corresponds to some symbol version. // a slice, where each element corresponds to some symbol version.
func (ctxt *Link) mkArchSymVec(name string, ver int, ls []loader.Sym) { func (ctxt *Link) mkArchSymVec(name string, ver int, ls []loader.Sym) {
ls[ver] = ctxt.loader.LookupOrCreateSym(name, ver) ls[ver] = ctxt.loader.LookupOrCreateSym(name, ver)
ctxt.loader.SetAttrReachable(ls[ver], true)
} }
// setArchSyms sets up the ArchSyms structure, and must be called before // setArchSyms sets up the ArchSyms structure, and must be called before
@ -1999,7 +2001,9 @@ func ldshlibsyms(ctxt *Link, shlib string) {
Errorf(nil, "cannot open shared library: %s", libpath) Errorf(nil, "cannot open shared library: %s", libpath)
return return
} }
defer f.Close() // Keep the file open as decodetypeGcprog needs to read from it.
// TODO: fix. Maybe mmap the file.
//defer f.Close()
hash, err := readnote(f, ELF_NOTE_GO_NAME, ELF_NOTE_GOABIHASH_TAG) hash, err := readnote(f, ELF_NOTE_GO_NAME, ELF_NOTE_GOABIHASH_TAG)
if err != nil { if err != nil {

View file

@ -14,7 +14,10 @@ func (out *OutBuf) fallocate(size uint64) error {
if err != nil { if err != nil {
return err return err
} }
cursize := uint64(stat.Size()) // F_PEOFPOSMODE allocates from the end of the file, so we want the size difference.
// Apparently, it uses the end of the allocation, instead of the logical end of the
// the file.
cursize := uint64(stat.Sys().(*syscall.Stat_t).Blocks * 512) // allocated size
if size <= cursize { if size <= cursize {
return nil return nil
} }
@ -23,7 +26,7 @@ func (out *OutBuf) fallocate(size uint64) error {
Flags: syscall.F_ALLOCATEALL, Flags: syscall.F_ALLOCATEALL,
Posmode: syscall.F_PEOFPOSMODE, Posmode: syscall.F_PEOFPOSMODE,
Offset: 0, Offset: 0,
Length: int64(size - cursize), // F_PEOFPOSMODE allocates from the end of the file, so we want the size difference here Length: int64(size - cursize),
} }
_, _, errno := syscall.Syscall(syscall.SYS_FCNTL, uintptr(out.f.Fd()), syscall.F_PREALLOCATE, uintptr(unsafe.Pointer(store))) _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, uintptr(out.f.Fd()), syscall.F_PREALLOCATE, uintptr(unsafe.Pointer(store)))

View file

@ -24,7 +24,7 @@ golang.org/x/arch/arm/armasm
golang.org/x/arch/arm64/arm64asm golang.org/x/arch/arm64/arm64asm
golang.org/x/arch/ppc64/ppc64asm golang.org/x/arch/ppc64/ppc64asm
golang.org/x/arch/x86/x86asm golang.org/x/arch/x86/x86asm
# golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79 # golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
## explicit ## explicit
golang.org/x/crypto/ed25519 golang.org/x/crypto/ed25519
golang.org/x/crypto/ed25519/internal/edwards25519 golang.org/x/crypto/ed25519/internal/edwards25519

View file

@ -164,7 +164,7 @@ type Signer interface {
// Sign signs digest with the private key, possibly using entropy from // Sign signs digest with the private key, possibly using entropy from
// rand. For an RSA key, the resulting signature should be either a // rand. For an RSA key, the resulting signature should be either a
// PKCS#1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA // PKCS #1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA
// key, it should be a DER-serialised, ASN.1 signature structure. // key, it should be a DER-serialised, ASN.1 signature structure.
// //
// Hash implements the SignerOpts interface and, in most cases, one can // Hash implements the SignerOpts interface and, in most cases, one can

View file

@ -27,7 +27,7 @@ import (
// exponentiation is larger than the modulus. (Otherwise it could be // exponentiation is larger than the modulus. (Otherwise it could be
// decrypted with a square-root.) // decrypted with a square-root.)
// //
// In these designs, when using PKCS#1 v1.5, it's vitally important to // In these designs, when using PKCS #1 v1.5, it's vitally important to
// avoid disclosing whether the received RSA message was well-formed // avoid disclosing whether the received RSA message was well-formed
// (that is, whether the result of decrypting is a correctly padded // (that is, whether the result of decrypting is a correctly padded
// message) because this leaks secret information. // message) because this leaks secret information.

View file

@ -14,9 +14,9 @@ import (
"crypto/internal/randutil" "crypto/internal/randutil"
) )
// This file implements encryption and decryption using PKCS#1 v1.5 padding. // This file implements encryption and decryption using PKCS #1 v1.5 padding.
// PKCS1v15DecrypterOpts is for passing options to PKCS#1 v1.5 decryption using // PKCS1v15DecrypterOpts is for passing options to PKCS #1 v1.5 decryption using
// the crypto.Decrypter interface. // the crypto.Decrypter interface.
type PKCS1v15DecryptOptions struct { type PKCS1v15DecryptOptions struct {
// SessionKeyLen is the length of the session key that is being // SessionKeyLen is the length of the session key that is being
@ -27,7 +27,7 @@ type PKCS1v15DecryptOptions struct {
} }
// EncryptPKCS1v15 encrypts the given message with RSA and the padding // EncryptPKCS1v15 encrypts the given message with RSA and the padding
// scheme from PKCS#1 v1.5. The message must be no longer than the // scheme from PKCS #1 v1.5. The message must be no longer than the
// length of the public modulus minus 11 bytes. // length of the public modulus minus 11 bytes.
// //
// The rand parameter is used as a source of entropy to ensure that // The rand parameter is used as a source of entropy to ensure that
@ -64,7 +64,7 @@ func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) ([]byte, error)
return c.FillBytes(em), nil return c.FillBytes(em), nil
} }
// DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5. // DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5.
// If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. // If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
// //
// Note that whether this function returns an error or not discloses secret // Note that whether this function returns an error or not discloses secret
@ -86,7 +86,7 @@ func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) ([]byt
return out[index:], nil return out[index:], nil
} }
// DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS#1 v1.5. // DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS #1 v1.5.
// If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. // If rand != nil, it uses RSA blinding to avoid timing side-channel attacks.
// It returns an error if the ciphertext is the wrong length or if the // It returns an error if the ciphertext is the wrong length or if the
// ciphertext is greater than the public modulus. Otherwise, no error is // ciphertext is greater than the public modulus. Otherwise, no error is
@ -216,7 +216,7 @@ var hashPrefixes = map[crypto.Hash][]byte{
} }
// SignPKCS1v15 calculates the signature of hashed using // SignPKCS1v15 calculates the signature of hashed using
// RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5. Note that hashed must // RSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5. Note that hashed must
// be the result of hashing the input message using the given hash // be the result of hashing the input message using the given hash
// function. If hash is zero, hashed is signed directly. This isn't // function. If hash is zero, hashed is signed directly. This isn't
// advisable except for interoperability. // advisable except for interoperability.
@ -258,7 +258,7 @@ func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []b
return c.FillBytes(em), nil return c.FillBytes(em), nil
} }
// VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature. // VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature.
// hashed is the result of hashing the input message using the given hash // hashed is the result of hashing the input message using the given hash
// function and sig is the signature. A valid signature is indicated by // function and sig is the signature. A valid signature is indicated by
// returning a nil error. If hash is zero then hashed is used directly. This // returning a nil error. If hash is zero then hashed is used directly. This

View file

@ -2,14 +2,14 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// Package rsa implements RSA encryption as specified in PKCS#1 and RFC 8017. // Package rsa implements RSA encryption as specified in PKCS #1 and RFC 8017.
// //
// RSA is a single, fundamental operation that is used in this package to // RSA is a single, fundamental operation that is used in this package to
// implement either public-key encryption or public-key signatures. // implement either public-key encryption or public-key signatures.
// //
// The original specification for encryption and signatures with RSA is PKCS#1 // The original specification for encryption and signatures with RSA is PKCS #1
// and the terms "RSA encryption" and "RSA signatures" by default refer to // and the terms "RSA encryption" and "RSA signatures" by default refer to
// PKCS#1 version 1.5. However, that specification has flaws and new designs // PKCS #1 version 1.5. However, that specification has flaws and new designs
// should use version 2, usually called by just OAEP and PSS, where // should use version 2, usually called by just OAEP and PSS, where
// possible. // possible.
// //
@ -134,7 +134,7 @@ func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool {
} }
// Sign signs digest with priv, reading randomness from rand. If opts is a // Sign signs digest with priv, reading randomness from rand. If opts is a
// *PSSOptions then the PSS algorithm will be used, otherwise PKCS#1 v1.5 will // *PSSOptions then the PSS algorithm will be used, otherwise PKCS #1 v1.5 will
// be used. digest must be the result of hashing the input message using // be used. digest must be the result of hashing the input message using
// opts.HashFunc(). // opts.HashFunc().
// //
@ -150,7 +150,7 @@ func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOp
} }
// Decrypt decrypts ciphertext with priv. If opts is nil or of type // Decrypt decrypts ciphertext with priv. If opts is nil or of type
// *PKCS1v15DecryptOptions then PKCS#1 v1.5 decryption is performed. Otherwise // *PKCS1v15DecryptOptions then PKCS #1 v1.5 decryption is performed. Otherwise
// opts must have type *OAEPOptions and OAEP decryption is done. // opts must have type *OAEPOptions and OAEP decryption is done.
func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) { func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
if opts == nil { if opts == nil {
@ -186,7 +186,7 @@ type PrecomputedValues struct {
// CRTValues is used for the 3rd and subsequent primes. Due to a // CRTValues is used for the 3rd and subsequent primes. Due to a
// historical accident, the CRT for the first two primes is handled // historical accident, the CRT for the first two primes is handled
// differently in PKCS#1 and interoperability is sufficiently // differently in PKCS #1 and interoperability is sufficiently
// important that we mirror this. // important that we mirror this.
CRTValues []CRTValue CRTValues []CRTValue
} }
@ -360,7 +360,7 @@ func incCounter(c *[4]byte) {
} }
// mgf1XOR XORs the bytes in out with a mask generated using the MGF1 function // mgf1XOR XORs the bytes in out with a mask generated using the MGF1 function
// specified in PKCS#1 v2.1. // specified in PKCS #1 v2.1.
func mgf1XOR(out []byte, hash hash.Hash, seed []byte) { func mgf1XOR(out []byte, hash hash.Hash, seed []byte) {
var counter [4]byte var counter [4]byte
var digest []byte var digest []byte

View file

@ -155,9 +155,9 @@ var rsaSignatureSchemes = []struct {
{PSSWithSHA256, crypto.SHA256.Size()*2 + 2, VersionTLS13}, {PSSWithSHA256, crypto.SHA256.Size()*2 + 2, VersionTLS13},
{PSSWithSHA384, crypto.SHA384.Size()*2 + 2, VersionTLS13}, {PSSWithSHA384, crypto.SHA384.Size()*2 + 2, VersionTLS13},
{PSSWithSHA512, crypto.SHA512.Size()*2 + 2, VersionTLS13}, {PSSWithSHA512, crypto.SHA512.Size()*2 + 2, VersionTLS13},
// PKCS#1 v1.5 uses prefixes from hashPrefixes in crypto/rsa, and requires // PKCS #1 v1.5 uses prefixes from hashPrefixes in crypto/rsa, and requires
// emLen >= len(prefix) + hLen + 11 // emLen >= len(prefix) + hLen + 11
// TLS 1.3 dropped support for PKCS#1 v1.5 in favor of RSA-PSS. // TLS 1.3 dropped support for PKCS #1 v1.5 in favor of RSA-PSS.
{PKCS1WithSHA256, 19 + crypto.SHA256.Size() + 11, VersionTLS12}, {PKCS1WithSHA256, 19 + crypto.SHA256.Size() + 11, VersionTLS12},
{PKCS1WithSHA384, 19 + crypto.SHA384.Size() + 11, VersionTLS12}, {PKCS1WithSHA384, 19 + crypto.SHA384.Size() + 11, VersionTLS12},
{PKCS1WithSHA512, 19 + crypto.SHA512.Size() + 11, VersionTLS12}, {PKCS1WithSHA512, 19 + crypto.SHA512.Size() + 11, VersionTLS12},

View file

@ -600,12 +600,12 @@ type Config struct {
// by the policy in ClientAuth. // by the policy in ClientAuth.
ClientCAs *x509.CertPool ClientCAs *x509.CertPool
// InsecureSkipVerify controls whether a client verifies the // InsecureSkipVerify controls whether a client verifies the server's
// server's certificate chain and host name. // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls
// If InsecureSkipVerify is true, TLS accepts any certificate // accepts any certificate presented by the server and any host name in that
// presented by the server and any host name in that certificate. // certificate. In this mode, TLS is susceptible to machine-in-the-middle
// In this mode, TLS is susceptible to machine-in-the-middle attacks. // attacks unless custom verification is used. This should be used only for
// This should be used only for testing. // testing or in combination with VerifyConnection or VerifyPeerCertificate.
InsecureSkipVerify bool InsecureSkipVerify bool
// CipherSuites is a list of supported cipher suites for TLS versions up to // CipherSuites is a list of supported cipher suites for TLS versions up to

View file

@ -81,6 +81,16 @@ func main() {
log.Fatalf("Failed to generate private key: %v", err) log.Fatalf("Failed to generate private key: %v", err)
} }
// ECDSA, ED25519 and RSA subject keys should have the DigitalSignature
// KeyUsage bits set in the x509.Certificate template
keyUsage := x509.KeyUsageDigitalSignature
// Only RSA subject keys should have the KeyEncipherment KeyUsage bits set. In
// the context of TLS this KeyUsage is particular to RSA key exchange and
// authentication.
if _, isRSA := priv.(*rsa.PrivateKey); isRSA {
keyUsage |= x509.KeyUsageKeyEncipherment
}
var notBefore time.Time var notBefore time.Time
if len(*validFrom) == 0 { if len(*validFrom) == 0 {
notBefore = time.Now() notBefore = time.Now()
@ -107,7 +117,7 @@ func main() {
NotBefore: notBefore, NotBefore: notBefore,
NotAfter: notAfter, NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, KeyUsage: keyUsage,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true, BasicConstraintsValid: true,
} }

View file

@ -40,7 +40,7 @@ func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certifi
if !ok { if !ok {
return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter") return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter")
} }
// Perform constant time RSA PKCS#1 v1.5 decryption // Perform constant time RSA PKCS #1 v1.5 decryption
preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48}) preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48})
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -365,7 +365,7 @@ func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
} }
// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys. // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys.
// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
func parsePrivateKey(der []byte) (crypto.PrivateKey, error) { func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {

View file

@ -1443,7 +1443,7 @@ func (s brokenSigner) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts
} }
// TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that // TestPKCS1OnlyCert uses a client certificate with a broken crypto.Signer that
// always makes PKCS#1 v1.5 signatures, so can't be used with RSA-PSS. // always makes PKCS #1 v1.5 signatures, so can't be used with RSA-PSS.
func TestPKCS1OnlyCert(t *testing.T) { func TestPKCS1OnlyCert(t *testing.T) {
clientConfig := testConfig.Clone() clientConfig := testConfig.Clone()
clientConfig.Certificates = []Certificate{{ clientConfig.Certificates = []Certificate{{
@ -1451,7 +1451,7 @@ func TestPKCS1OnlyCert(t *testing.T) {
PrivateKey: brokenSigner{testRSAPrivateKey}, PrivateKey: brokenSigner{testRSAPrivateKey},
}} }}
serverConfig := testConfig.Clone() serverConfig := testConfig.Clone()
serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS#1 v1.5 serverConfig.MaxVersion = VersionTLS12 // TLS 1.3 doesn't support PKCS #1 v1.5
serverConfig.ClientAuth = RequireAnyClientCert serverConfig.ClientAuth = RequireAnyClientCert
// If RSA-PSS is selected, the handshake should fail. // If RSA-PSS is selected, the handshake should fail.

View file

@ -11,7 +11,7 @@ import (
"math/big" "math/big"
) )
// pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key. // pkcs1PrivateKey is a structure which mirrors the PKCS #1 ASN.1 for an RSA private key.
type pkcs1PrivateKey struct { type pkcs1PrivateKey struct {
Version int Version int
N *big.Int N *big.Int
@ -35,13 +35,13 @@ type pkcs1AdditionalRSAPrime struct {
Coeff *big.Int Coeff *big.Int
} }
// pkcs1PublicKey reflects the ASN.1 structure of a PKCS#1 public key. // pkcs1PublicKey reflects the ASN.1 structure of a PKCS #1 public key.
type pkcs1PublicKey struct { type pkcs1PublicKey struct {
N *big.Int N *big.Int
E int E int
} }
// ParsePKCS1PrivateKey parses an RSA private key in PKCS#1, ASN.1 DER form. // ParsePKCS1PrivateKey parses an RSA private key in PKCS #1, ASN.1 DER form.
// //
// This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY". // This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".
func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error) { func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error) {
@ -96,7 +96,7 @@ func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error) {
return key, nil return key, nil
} }
// MarshalPKCS1PrivateKey converts an RSA private key to PKCS#1, ASN.1 DER form. // MarshalPKCS1PrivateKey converts an RSA private key to PKCS #1, ASN.1 DER form.
// //
// This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY". // This kind of key is commonly encoded in PEM blocks of type "RSA PRIVATE KEY".
// For a more flexible key format which is not RSA specific, use // For a more flexible key format which is not RSA specific, use
@ -132,7 +132,7 @@ func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
return b return b
} }
// ParsePKCS1PublicKey parses an RSA public key in PKCS#1, ASN.1 DER form. // ParsePKCS1PublicKey parses an RSA public key in PKCS #1, ASN.1 DER form.
// //
// This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY". // This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".
func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error) { func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error) {
@ -161,7 +161,7 @@ func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error) {
}, nil }, nil
} }
// MarshalPKCS1PublicKey converts an RSA public key to PKCS#1, ASN.1 DER form. // MarshalPKCS1PublicKey converts an RSA public key to PKCS #1, ASN.1 DER form.
// //
// This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY". // This kind of key is commonly encoded in PEM blocks of type "RSA PUBLIC KEY".
func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte { func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte {

View file

@ -14,7 +14,7 @@ import (
"fmt" "fmt"
) )
// pkcs8 reflects an ASN.1, PKCS#8 PrivateKey. See // pkcs8 reflects an ASN.1, PKCS #8 PrivateKey. See
// ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn
// and RFC 5208. // and RFC 5208.
type pkcs8 struct { type pkcs8 struct {
@ -24,7 +24,7 @@ type pkcs8 struct {
// optional attributes omitted. // optional attributes omitted.
} }
// ParsePKCS8PrivateKey parses an unencrypted private key in PKCS#8, ASN.1 DER form. // ParsePKCS8PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER form.
// //
// It returns a *rsa.PrivateKey, a *ecdsa.PrivateKey, or a ed25519.PrivateKey. // It returns a *rsa.PrivateKey, a *ecdsa.PrivateKey, or a ed25519.PrivateKey.
// More types might be supported in the future. // More types might be supported in the future.
@ -79,7 +79,7 @@ func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) {
} }
} }
// MarshalPKCS8PrivateKey converts a private key to PKCS#8, ASN.1 DER form. // MarshalPKCS8PrivateKey converts a private key to PKCS #8, ASN.1 DER form.
// //
// The following key types are currently supported: *rsa.PrivateKey, *ecdsa.PrivateKey // The following key types are currently supported: *rsa.PrivateKey, *ecdsa.PrivateKey
// and ed25519.PrivateKey. Unsupported key types result in an error. // and ed25519.PrivateKey. Unsupported key types result in an error.

View file

@ -247,20 +247,26 @@ func (n Name) ToRDNSequence() (ret RDNSequence) {
// String returns the string form of n, roughly following // String returns the string form of n, roughly following
// the RFC 2253 Distinguished Names syntax. // the RFC 2253 Distinguished Names syntax.
func (n Name) String() string { func (n Name) String() string {
if len(n.ExtraNames) == 0 { var rdns RDNSequence
// If there are no ExtraNames, surface the parsed value (all entries in
// Names) instead.
if n.ExtraNames == nil {
for _, atv := range n.Names { for _, atv := range n.Names {
t := atv.Type t := atv.Type
if len(t) == 4 && t[0] == 2 && t[1] == 5 && t[2] == 4 { if len(t) == 4 && t[0] == 2 && t[1] == 5 && t[2] == 4 {
switch t[3] { switch t[3] {
case 3, 5, 6, 7, 8, 9, 10, 11, 17: case 3, 5, 6, 7, 8, 9, 10, 11, 17:
// These attributes are already parsed into named fields. // These attributes were already parsed into named fields.
continue continue
} }
} }
n.ExtraNames = append(n.ExtraNames, atv) // Place non-standard parsed values at the beginning of the sequence
// so they will be at the end of the string. See Issue 39924.
rdns = append(rdns, []AttributeTypeAndValue{atv})
} }
} }
return n.ToRDNSequence().String() rdns = append(rdns, n.ToRDNSequence()...)
return rdns.String()
} }
// oidInAttributeTypeAndValue reports whether a type with the given OID exists // oidInAttributeTypeAndValue reports whether a type with the given OID exists

View file

@ -8,7 +8,7 @@ package x509
import ( import (
"bytes" "bytes"
"crypto/x509/internal/macOS" macOS "crypto/x509/internal/macos"
"fmt" "fmt"
"os" "os"
"strings" "strings"

View file

@ -2349,7 +2349,7 @@ type certificateRequest struct {
SignatureValue asn1.BitString SignatureValue asn1.BitString
} }
// oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
// extensions in a CSR. // extensions in a CSR.
var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14} var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}

View file

@ -2076,10 +2076,31 @@ func TestPKIXNameString(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
// Check that parsed non-standard attributes are printed.
rdns := pkix.Name{
Locality: []string{"Gophertown"},
ExtraNames: []pkix.AttributeTypeAndValue{
{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
}.ToRDNSequence()
nn := pkix.Name{}
nn.FillFromRDNSequence(&rdns)
// Check that zero-length non-nil ExtraNames hide Names.
extra := []pkix.AttributeTypeAndValue{
{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "backing array"}}
extraNotNil := pkix.Name{
Locality: []string{"Gophertown"},
ExtraNames: extra[:0],
Names: []pkix.AttributeTypeAndValue{
{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
}
tests := []struct { tests := []struct {
dn pkix.Name dn pkix.Name
want string want string
}{ }{
{nn, "L=Gophertown,1.2.3.4.5=#130a676f6c616e672e6f7267"},
{extraNotNil, "L=Gophertown"},
{pkix.Name{ {pkix.Name{
CommonName: "Steve Kille", CommonName: "Steve Kille",
Organization: []string{"Isode Limited"}, Organization: []string{"Isode Limited"},
@ -2108,6 +2129,20 @@ func TestPKIXNameString(t *testing.T) {
ExtraNames: []pkix.AttributeTypeAndValue{ ExtraNames: []pkix.AttributeTypeAndValue{
{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}}, {Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
}, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"}, }, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
// If there are no ExtraNames, the Names are printed instead.
{pkix.Name{
Locality: []string{"Gophertown"},
Names: []pkix.AttributeTypeAndValue{
{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
}, "L=Gophertown,1.2.3.4.5=#130a676f6c616e672e6f7267"},
// If there are both, print only the ExtraNames.
{pkix.Name{
Locality: []string{"Gophertown"},
ExtraNames: []pkix.AttributeTypeAndValue{
{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
Names: []pkix.AttributeTypeAndValue{
{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 6}), Value: "example.com"}},
}, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
} }
for i, test := range tests { for i, test := range tests {
@ -2115,6 +2150,10 @@ func TestPKIXNameString(t *testing.T) {
t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want) t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
} }
} }
if extra[0].Value != "backing array" {
t.Errorf("the backing array of an empty ExtraNames got modified by String")
}
} }
func TestRDNSequenceString(t *testing.T) { func TestRDNSequenceString(t *testing.T) {

View file

@ -177,7 +177,8 @@ func (d *decodeState) unmarshal(v interface{}) error {
d.scanWhile(scanSkipSpace) d.scanWhile(scanSkipSpace)
// We decode rv not rv.Elem because the Unmarshaler interface // We decode rv not rv.Elem because the Unmarshaler interface
// test must be applied at the top level of the value. // test must be applied at the top level of the value.
if err := d.value(rv); err != nil { err := d.value(rv)
if err != nil {
return d.addErrorContext(err) return d.addErrorContext(err)
} }
return d.savedError return d.savedError
@ -507,7 +508,6 @@ func (d *decodeState) array(v reflect.Value) error {
return nil return nil
} }
v = pv v = pv
initialSliceCap := 0
// Check type of target. // Check type of target.
switch v.Kind() { switch v.Kind() {
@ -524,9 +524,8 @@ func (d *decodeState) array(v reflect.Value) error {
d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)}) d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)})
d.skip() d.skip()
return nil return nil
case reflect.Slice: case reflect.Array, reflect.Slice:
initialSliceCap = v.Cap() break
case reflect.Array:
} }
i := 0 i := 0
@ -537,6 +536,7 @@ func (d *decodeState) array(v reflect.Value) error {
break break
} }
// Get element of array, growing if necessary.
if v.Kind() == reflect.Slice { if v.Kind() == reflect.Slice {
// Grow slice if necessary // Grow slice if necessary
if i >= v.Cap() { if i >= v.Cap() {
@ -552,22 +552,19 @@ func (d *decodeState) array(v reflect.Value) error {
v.SetLen(i + 1) v.SetLen(i + 1)
} }
} }
var into reflect.Value
if i < v.Len() { if i < v.Len() {
into = v.Index(i) // Decode into element.
if i < initialSliceCap { if err := d.value(v.Index(i)); err != nil {
// Reusing an element from the slice's original return err
// backing array; zero it before decoding. }
into.Set(reflect.Zero(v.Type().Elem())) } else {
// Ran out of fixed array: skip.
if err := d.value(reflect.Value{}); err != nil {
return err
} }
} }
i++ i++
// Note that we decode the value even if we ran past the end of
// the fixed array. In that case, we decode into an empty value
// and do nothing with it.
if err := d.value(into); err != nil {
return err
}
// Next token must be , or ]. // Next token must be , or ].
if d.opcode == scanSkipSpace { if d.opcode == scanSkipSpace {
@ -583,17 +580,16 @@ func (d *decodeState) array(v reflect.Value) error {
if i < v.Len() { if i < v.Len() {
if v.Kind() == reflect.Array { if v.Kind() == reflect.Array {
// Zero the remaining elements. // Array. Zero the rest.
zero := reflect.Zero(v.Type().Elem()) z := reflect.Zero(v.Type().Elem())
for ; i < v.Len(); i++ { for ; i < v.Len(); i++ {
v.Index(i).Set(zero) v.Index(i).Set(z)
} }
} else { } else {
v.SetLen(i) v.SetLen(i)
} }
} }
if v.Kind() == reflect.Slice && v.IsNil() { if i == 0 && v.Kind() == reflect.Slice {
// Don't allow the resulting slice to be nil.
v.Set(reflect.MakeSlice(v.Type(), 0, 0)) v.Set(reflect.MakeSlice(v.Type(), 0, 0))
} }
return nil return nil

View file

@ -2099,10 +2099,7 @@ func TestSkipArrayObjects(t *testing.T) {
// slices, and arrays. // slices, and arrays.
// Issues 4900 and 8837, among others. // Issues 4900 and 8837, among others.
func TestPrefilled(t *testing.T) { func TestPrefilled(t *testing.T) {
type T struct { // Values here change, cannot reuse table across runs.
A, B int
}
// Values here change, cannot reuse the table across runs.
var prefillTests = []struct { var prefillTests = []struct {
in string in string
ptr interface{} ptr interface{}
@ -2138,16 +2135,6 @@ func TestPrefilled(t *testing.T) {
ptr: &[...]int{1, 2}, ptr: &[...]int{1, 2},
out: &[...]int{3, 0}, out: &[...]int{3, 0},
}, },
{
in: `[{"A": 3}]`,
ptr: &[]T{{A: -1, B: -2}, {A: -3, B: -4}},
out: &[]T{{A: 3}},
},
{
in: `[{"A": 3}]`,
ptr: &[...]T{{A: -1, B: -2}, {A: -3, B: -4}},
out: &[...]T{{A: 3, B: -2}, {}},
},
} }
for _, tt := range prefillTests { for _, tt := range prefillTests {

View file

@ -345,11 +345,8 @@ func (p *printer) createAttrPrefix(url string) string {
if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") { if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") {
prefix = "_" prefix = "_"
} }
// xmlanything is reserved and any variant of it regardless of if strings.HasPrefix(prefix, "xml") {
// case should be matched, so: // xmlanything is reserved.
// (('X'|'x') ('M'|'m') ('L'|'l'))
// See Section 2.3 of https://www.w3.org/TR/REC-xml/
if len(prefix) >= 3 && strings.EqualFold(prefix[:3], "xml") {
prefix = "_" + prefix prefix = "_" + prefix
} }
if p.attrNS[prefix] != "" { if p.attrNS[prefix] != "" {

View file

@ -2283,30 +2283,6 @@ var encodeTokenTests = []struct {
}}, }},
}, },
want: `<foo xmlns="space"><bar xmlns="space" xmlns:space="space" space:attr="value">`, want: `<foo xmlns="space"><bar xmlns="space" xmlns:space="space" space:attr="value">`,
}, {
desc: "reserved namespace prefix -- all lower case",
toks: []Token{
StartElement{Name{"", "foo"}, []Attr{
{Name{"http://www.w3.org/2001/xmlSchema-instance", "nil"}, "true"},
}},
},
want: `<foo xmlns:_xmlSchema-instance="http://www.w3.org/2001/xmlSchema-instance" _xmlSchema-instance:nil="true">`,
}, {
desc: "reserved namespace prefix -- all upper case",
toks: []Token{
StartElement{Name{"", "foo"}, []Attr{
{Name{"http://www.w3.org/2001/XMLSchema-instance", "nil"}, "true"},
}},
},
want: `<foo xmlns:_XMLSchema-instance="http://www.w3.org/2001/XMLSchema-instance" _XMLSchema-instance:nil="true">`,
}, {
desc: "reserved namespace prefix -- all mixed case",
toks: []Token{
StartElement{Name{"", "foo"}, []Attr{
{Name{"http://www.w3.org/2001/XmLSchema-instance", "nil"}, "true"},
}},
},
want: `<foo xmlns:_XmLSchema-instance="http://www.w3.org/2001/XmLSchema-instance" _XmLSchema-instance:nil="true">`,
}} }}
func TestEncodeToken(t *testing.T) { func TestEncodeToken(t *testing.T) {

View file

@ -3,8 +3,8 @@ module std
go 1.15 go 1.15
require ( require (
golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79 golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5 golang.org/x/net v0.0.0-20200707034311-ab3426394381
golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3 // indirect golang.org/x/sys v0.0.0-20200501145240-bc7a7d42d5c3 // indirect
golang.org/x/text v0.3.3-0.20200430171850-afb9336c4530 // indirect golang.org/x/text v0.3.3-0.20200430171850-afb9336c4530 // indirect
) )

View file

@ -1,9 +1,9 @@
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79 h1:IaQbIIB2X/Mp/DKctl6ROxz1KyMlKp4uyvL6+kQ7C88= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5 h1:WQ8q63x+f/zpC8Ac1s9wLElVoHhm32p6tudrU72n1QA= golang.org/x/net v0.0.0-20200707034311-ab3426394381 h1:VXak5I6aEWmAXeQjA+QSZzlgNrpq9mjcfDemuexIKsU=
golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

View file

@ -16,7 +16,6 @@ import (
"internal/goversion" "internal/goversion"
"io" "io"
"io/ioutil" "io/ioutil"
"log"
"os" "os"
"os/exec" "os/exec"
pathpkg "path" pathpkg "path"
@ -924,7 +923,7 @@ Found:
quoted := spec.Path.Value quoted := spec.Path.Value
path, err := strconv.Unquote(quoted) path, err := strconv.Unquote(quoted)
if err != nil { if err != nil {
log.Panicf("%s: parser returned invalid quoted string: <%s>", filename, quoted) panic(fmt.Sprintf("%s: parser returned invalid quoted string: <%s>", filename, quoted))
} }
fileImports = append(fileImports, importPos{path, spec.Pos()}) fileImports = append(fileImports, importPos{path, spec.Pos()})
if path == "C" { if path == "C" {

File diff suppressed because it is too large Load diff

View file

@ -413,6 +413,7 @@ func checkIfNoneMatch(w ResponseWriter, r *Request) condResult {
} }
if buf[0] == ',' { if buf[0] == ',' {
buf = buf[1:] buf = buf[1:]
continue
} }
if buf[0] == '*' { if buf[0] == '*' {
return condFalse return condFalse

View file

@ -849,6 +849,15 @@ func TestServeContent(t *testing.T) {
wantStatus: 200, wantStatus: 200,
wantContentType: "text/css; charset=utf-8", wantContentType: "text/css; charset=utf-8",
}, },
"if_none_match_malformed": {
file: "testdata/style.css",
serveETag: `"foo"`,
reqHeader: map[string]string{
"If-None-Match": `,`,
},
wantStatus: 200,
wantContentType: "text/css; charset=utf-8",
},
"range_good": { "range_good": {
file: "testdata/style.css", file: "testdata/style.css",
serveETag: `"A"`, serveETag: `"A"`,

View file

@ -68,8 +68,8 @@ func readInterface(i int) (*Interface, error) {
} }
ifc.MTU = mtu ifc.MTU = mtu
// Not a loopback device // Not a loopback device ("/dev/null") or packet interface (e.g. "pkt2")
if device != "/dev/null" { if stringsHasPrefix(device, netdir+"/") {
deviceaddrf, err := open(device + "/addr") deviceaddrf, err := open(device + "/addr")
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -67,7 +67,7 @@ func parsePlan9Addr(s string) (ip IP, iport int, err error) {
return addr, p, nil return addr, p, nil
} }
func readPlan9Addr(proto, filename string) (addr Addr, err error) { func readPlan9Addr(net, filename string) (addr Addr, err error) {
var buf [128]byte var buf [128]byte
f, err := os.Open(filename) f, err := os.Open(filename)
@ -83,13 +83,19 @@ func readPlan9Addr(proto, filename string) (addr Addr, err error) {
if err != nil { if err != nil {
return return
} }
switch proto { switch net {
case "tcp": case "tcp4", "udp4":
if ip.Equal(IPv6zero) {
ip = ip[:IPv4len]
}
}
switch net {
case "tcp", "tcp4", "tcp6":
addr = &TCPAddr{IP: ip, Port: port} addr = &TCPAddr{IP: ip, Port: port}
case "udp": case "udp", "udp4", "udp6":
addr = &UDPAddr{IP: ip, Port: port} addr = &UDPAddr{IP: ip, Port: port}
default: default:
return nil, UnknownNetworkError(proto) return nil, UnknownNetworkError(net)
} }
return addr, nil return addr, nil
} }
@ -199,7 +205,11 @@ func dialPlan9Blocking(ctx context.Context, net string, laddr, raddr Addr) (fd *
if err != nil { if err != nil {
return nil, err return nil, err
} }
_, err = f.WriteString("connect " + dest) if la := plan9LocalAddr(laddr); la == "" {
err = hangupCtlWrite(ctx, proto, f, "connect "+dest)
} else {
err = hangupCtlWrite(ctx, proto, f, "connect "+dest+" "+la)
}
if err != nil { if err != nil {
f.Close() f.Close()
return nil, err return nil, err
@ -209,7 +219,7 @@ func dialPlan9Blocking(ctx context.Context, net string, laddr, raddr Addr) (fd *
f.Close() f.Close()
return nil, err return nil, err
} }
laddr, err = readPlan9Addr(proto, netdir+"/"+proto+"/"+name+"/local") laddr, err = readPlan9Addr(net, netdir+"/"+proto+"/"+name+"/local")
if err != nil { if err != nil {
data.Close() data.Close()
f.Close() f.Close()
@ -229,7 +239,7 @@ func listenPlan9(ctx context.Context, net string, laddr Addr) (fd *netFD, err er
f.Close() f.Close()
return nil, &OpError{Op: "announce", Net: net, Source: laddr, Addr: nil, Err: err} return nil, &OpError{Op: "announce", Net: net, Source: laddr, Addr: nil, Err: err}
} }
laddr, err = readPlan9Addr(proto, netdir+"/"+proto+"/"+name+"/local") laddr, err = readPlan9Addr(net, netdir+"/"+proto+"/"+name+"/local")
if err != nil { if err != nil {
f.Close() f.Close()
return nil, err return nil, err
@ -303,3 +313,53 @@ func toLocal(a Addr, net string) Addr {
} }
return a return a
} }
// plan9LocalAddr returns a Plan 9 local address string.
// See setladdrport at https://9p.io/sources/plan9/sys/src/9/ip/devip.c.
func plan9LocalAddr(addr Addr) string {
var ip IP
port := 0
switch a := addr.(type) {
case *TCPAddr:
if a != nil {
ip = a.IP
port = a.Port
}
case *UDPAddr:
if a != nil {
ip = a.IP
port = a.Port
}
}
if len(ip) == 0 || ip.IsUnspecified() {
if port == 0 {
return ""
}
return itoa(port)
}
return ip.String() + "!" + itoa(port)
}
func hangupCtlWrite(ctx context.Context, proto string, ctl *os.File, msg string) error {
if proto != "tcp" {
_, err := ctl.WriteString(msg)
return err
}
written := make(chan struct{})
errc := make(chan error)
go func() {
select {
case <-ctx.Done():
ctl.WriteString("hangup")
errc <- mapErr(ctx.Err())
case <-written:
errc <- nil
}
}()
_, err := ctl.WriteString(msg)
close(written)
if e := <-errc; err == nil && e != nil { // we hung up
return e
}
return err
}

View file

@ -0,0 +1,29 @@
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package net
import "testing"
func TestTCP4ListenZero(t *testing.T) {
l, err := Listen("tcp4", "0.0.0.0:0")
if err != nil {
t.Fatal(err)
}
defer l.Close()
if a := l.Addr(); isNotIPv4(a) {
t.Errorf("address does not contain IPv4: %v", a)
}
}
func TestUDP4ListenZero(t *testing.T) {
c, err := ListenPacket("udp4", "0.0.0.0:0")
if err != nil {
t.Fatal(err)
}
defer c.Close()
if a := c.LocalAddr(); isNotIPv4(a) {
t.Errorf("address does not contain IPv4: %v", a)
}
}

View file

@ -88,7 +88,7 @@ func (r *Reader) readLineSlice() ([]byte, error) {
// The first call to ReadContinuedLine will return "Line 1 continued..." // The first call to ReadContinuedLine will return "Line 1 continued..."
// and the second will return "Line 2". // and the second will return "Line 2".
// //
// A line consisting of only white space is never continued. // Empty lines are never continued.
// //
func (r *Reader) ReadContinuedLine() (string, error) { func (r *Reader) ReadContinuedLine() (string, error) {
line, err := r.readContinuedLineSlice(noValidation) line, err := r.readContinuedLineSlice(noValidation)

View file

@ -104,6 +104,25 @@ func TestStdPipe(t *testing.T) {
} }
} }
} }
// Test redirecting stdout but not stderr. Issue 40076.
cmd := osexec.Command(os.Args[0], "-test.run", "TestStdPipeHelper")
cmd.Stdout = w
var stderr bytes.Buffer
cmd.Stderr = &stderr
cmd.Env = append(os.Environ(), "GO_TEST_STD_PIPE_HELPER=1")
if err := cmd.Run(); err == nil {
t.Errorf("unexpected success of write to closed stdout")
} else if ee, ok := err.(*osexec.ExitError); !ok {
t.Errorf("unexpected exec error type %T: %v", err, err)
} else if ws, ok := ee.Sys().(syscall.WaitStatus); !ok {
t.Errorf("unexpected wait status type %T: %v", ee.Sys(), ee.Sys())
} else if !ws.Signaled() || ws.Signal() != syscall.SIGPIPE {
t.Errorf("unexpected exit status %v for write to closed stdout", err)
}
if output := stderr.Bytes(); len(output) > 0 {
t.Errorf("unexpected output on stderr: %s", output)
}
} }
// This is a helper for TestStdPipe. It's not a test in itself. // This is a helper for TestStdPipe. It's not a test in itself.

View file

@ -32,6 +32,11 @@ func (f *File) readFrom(r io.Reader) (written int64, handled bool, err error) {
if !ok { if !ok {
return 0, false, nil return 0, false, nil
} }
if src.checkValid("ReadFrom") != nil {
// Avoid returning the error as we report handled as false,
// leave further error handling as the responsibility of the caller.
return 0, false, nil
}
written, handled, err = pollCopyFileRange(&f.pfd, &src.pfd, remain) written, handled, err = pollCopyFileRange(&f.pfd, &src.pfd, remain)
if lr != nil { if lr != nil {

View file

@ -8,6 +8,7 @@ import (
"bytes" "bytes"
"internal/poll" "internal/poll"
"io" "io"
"io/ioutil"
"math/rand" "math/rand"
. "os" . "os"
"path/filepath" "path/filepath"
@ -170,6 +171,35 @@ func TestCopyFileRange(t *testing.T) {
mustContainData(t, dst, data) mustContainData(t, dst, data)
}) })
}) })
t.Run("Nil", func(t *testing.T) {
var nilFile *File
anyFile, err := ioutil.TempFile("", "")
if err != nil {
t.Fatal(err)
}
defer Remove(anyFile.Name())
defer anyFile.Close()
if _, err := io.Copy(nilFile, nilFile); err != ErrInvalid {
t.Errorf("io.Copy(nilFile, nilFile) = %v, want %v", err, ErrInvalid)
}
if _, err := io.Copy(anyFile, nilFile); err != ErrInvalid {
t.Errorf("io.Copy(anyFile, nilFile) = %v, want %v", err, ErrInvalid)
}
if _, err := io.Copy(nilFile, anyFile); err != ErrInvalid {
t.Errorf("io.Copy(nilFile, anyFile) = %v, want %v", err, ErrInvalid)
}
if _, err := nilFile.ReadFrom(nilFile); err != ErrInvalid {
t.Errorf("nilFile.ReadFrom(nilFile) = %v, want %v", err, ErrInvalid)
}
if _, err := anyFile.ReadFrom(nilFile); err != ErrInvalid {
t.Errorf("anyFile.ReadFrom(nilFile) = %v, want %v", err, ErrInvalid)
}
if _, err := nilFile.ReadFrom(anyFile); err != ErrInvalid {
t.Errorf("nilFile.ReadFrom(anyFile) = %v, want %v", err, ErrInvalid)
}
})
} }
func testCopyFileRange(t *testing.T, size int64, limit int64) { func testCopyFileRange(t *testing.T, size int64, limit int64) {

View file

@ -310,14 +310,14 @@ func glob(dir, pattern string, matches []string) (m []string, e error) {
m = matches m = matches
fi, err := os.Stat(dir) fi, err := os.Stat(dir)
if err != nil { if err != nil {
return return // ignore I/O error
} }
if !fi.IsDir() { if !fi.IsDir() {
return return // ignore I/O error
} }
d, err := os.Open(dir) d, err := os.Open(dir)
if err != nil { if err != nil {
return return // ignore I/O error
} }
defer d.Close() defer d.Close()

View file

@ -303,6 +303,8 @@ const (
// On other platforms, the user address space is contiguous // On other platforms, the user address space is contiguous
// and starts at 0, so no offset is necessary. // and starts at 0, so no offset is necessary.
arenaBaseOffset = 0xffff800000000000*sys.GoarchAmd64 + 0x0a00000000000000*sys.GoosAix arenaBaseOffset = 0xffff800000000000*sys.GoarchAmd64 + 0x0a00000000000000*sys.GoosAix
// A typed version of this constant that will make it into DWARF (for viewcore).
arenaBaseOffsetUintptr = uintptr(arenaBaseOffset)
// Max number of threads to run garbage collection. // Max number of threads to run garbage collection.
// 2, 3, and 4 are all plausible maximums depending // 2, 3, and 4 are all plausible maximums depending

View file

@ -340,6 +340,7 @@ func osStackRemap(s *mspan, flags int32) {
} }
} }
//go:nosplit
func raise(sig uint32) { func raise(sig uint32) {
thrkill(getthrid(), int(sig)) thrkill(getthrid(), int(sig))
} }

View file

@ -129,7 +129,7 @@ func syscall_rawSyscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintpt
// syscallNoErr is used in crypto/x509 to call into Security.framework and CF. // syscallNoErr is used in crypto/x509 to call into Security.framework and CF.
//go:linkname crypto_x509_syscall crypto/x509/internal/macOS.syscall //go:linkname crypto_x509_syscall crypto/x509/internal/macos.syscall
//go:nosplit //go:nosplit
//go:cgo_unsafe_args //go:cgo_unsafe_args
func crypto_x509_syscall(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1 uintptr) { func crypto_x509_syscall(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1 uintptr) {

View file

@ -230,12 +230,12 @@ func (b *Builder) AddASN1(tag asn1.Tag, f BuilderContinuation) {
// String // String
// ReadASN1Boolean decodes an ASN.1 INTEGER and converts it to a boolean // ReadASN1Boolean decodes an ASN.1 BOOLEAN and converts it to a boolean
// representation into out and advances. It reports whether the read // representation into out and advances. It reports whether the read
// was successful. // was successful.
func (s *String) ReadASN1Boolean(out *bool) bool { func (s *String) ReadASN1Boolean(out *bool) bool {
var bytes String var bytes String
if !s.ReadASN1(&bytes, asn1.INTEGER) || len(bytes) != 1 { if !s.ReadASN1(&bytes, asn1.BOOLEAN) || len(bytes) != 1 {
return false return false
} }

View file

@ -14,7 +14,6 @@ package dnsmessage
import ( import (
"errors" "errors"
"fmt"
) )
// Message formats // Message formats
@ -2141,7 +2140,7 @@ func unpackResourceBody(msg []byte, off int, hdr ResourceHeader) (ResourceBody,
return nil, off, &nestedError{name + " record", err} return nil, off, &nestedError{name + " record", err}
} }
if r == nil { if r == nil {
return nil, off, fmt.Errorf("invalid resource type: %d", hdr.Type) return nil, off, errors.New("invalid resource type: " + hdr.Type.String())
} }
return r, off + int(hdr.Length), nil return r, off + int(hdr.Length), nil
} }

View file

@ -1,4 +1,4 @@
# golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79 # golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
## explicit ## explicit
golang.org/x/crypto/chacha20 golang.org/x/crypto/chacha20
golang.org/x/crypto/chacha20poly1305 golang.org/x/crypto/chacha20poly1305
@ -8,7 +8,7 @@ golang.org/x/crypto/curve25519
golang.org/x/crypto/hkdf golang.org/x/crypto/hkdf
golang.org/x/crypto/internal/subtle golang.org/x/crypto/internal/subtle
golang.org/x/crypto/poly1305 golang.org/x/crypto/poly1305
# golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5 # golang.org/x/net v0.0.0-20200707034311-ab3426394381
## explicit ## explicit
golang.org/x/net/dns/dnsmessage golang.org/x/net/dns/dnsmessage
golang.org/x/net/http/httpguts golang.org/x/net/http/httpguts