Skip to content

Instantly share code, notes, and snippets.

@stevemk14ebr
Created January 13, 2025 20:37
Show Gist options
  • Save stevemk14ebr/c5bdc031a341ba02126ead928645b133 to your computer and use it in GitHub Desktop.
Save stevemk14ebr/c5bdc031a341ba02126ead928645b133 to your computer and use it in GitHub Desktop.
go list std | while read -r pkg; do echo "\n$pkg"; go doc -u -all "$pkg" | awk '/^FUNCTIONS/ {p=1;next} p && !/\/\// { print }'; done > ~/go_package_list.txt
This file has been truncated, but you can view the full file.
archive/tar
func blockPadding(offset int64) (n int64)
blockPadding computes the number of bytes needed to pad offset up to the
nearest block edge where 0 <= n < blockSize.
func discard(r io.Reader, n int64) error
discard skips n bytes in r, reporting an error if unable to do so.
func ensureEOF(r io.Reader) error
ensureEOF checks whether r is at EOF, reporting ErrWriteTooLong if not so.
func fitsInBase256(n int, x int64) bool
fitsInBase256 reports whether x can be encoded into n bytes using base-256
encoding. Unlike octal encoding, base-256 encoding does not require that
the string ends with a NUL character. Thus, all n bytes are available for
output.
If operating in binary mode, this assumes strict GNU binary mode; which
means that the first byte can only be either 0x80 or 0xff. Thus, the first
byte is equivalent to the sign bit in two's complement form.
func fitsInOctal(n int, x int64) bool
fitsInOctal reports whether the integer x fits in a field n-bytes long using
octal encoding with the appropriate NUL terminator.
func formatPAXRecord(k, v string) (string, error)
formatPAXRecord formats a single PAX record, prefixing it with the
appropriate length.
func formatPAXTime(ts time.Time) (s string)
formatPAXTime converts ts into a time of the form %d.%d as described in the
PAX specification. This function is capable of negative timestamps.
func hasNUL(s string) bool
hasNUL reports whether the NUL character exists within s.
func init()
func isASCII(s string) bool
isASCII reports whether the input is an ASCII C-style string.
func isHeaderOnlyType(flag byte) bool
isHeaderOnlyType checks if the given type flag is of the type that has no
data section even if a size is specified.
func mergePAX(hdr *Header, paxHdrs map[string]string) (err error)
mergePAX merges paxHdrs into hdr for all relevant fields of Header.
func mustReadFull(r io.Reader, b []byte) (int, error)
mustReadFull is like io.ReadFull except it returns io.ErrUnexpectedEOF when
io.EOF is hit before len(b) bytes are read.
func parsePAX(r io.Reader) (map[string]string, error)
parsePAX parses PAX headers. If an extended header (type 'x') is invalid,
ErrHeader is returned.
func parsePAXRecord(s string) (k, v, r string, err error)
parsePAXRecord parses the input PAX record string into a key-value pair.
If parsing is successful, it will slice off the currently read record and
return the remainder as r.
func parsePAXTime(s string) (time.Time, error)
parsePAXTime takes a string of the form %d.%d as described in the PAX
specification. Note that this implementation allows for negative timestamps,
which is allowed for by the PAX specification, but not always portable.
func readSpecialFile(r io.Reader) ([]byte, error)
readSpecialFile is like io.ReadAll except it returns ErrFieldTooLong if more
than maxSpecialFileSize is read.
func splitUSTARPath(name string) (prefix, suffix string, ok bool)
splitUSTARPath splits a path according to USTAR prefix and suffix rules.
If the path is not splittable, then it will return ("", "", false).
func statAtime(st *syscall.Stat_t) time.Time
func statCtime(st *syscall.Stat_t) time.Time
func statUnix(fi fs.FileInfo, h *Header, doNameLookups bool) error
func toASCII(s string) string
toASCII converts the input to an ASCII C-style string. This is a best effort
conversion, so invalid characters are dropped.
func tryReadFull(r io.Reader, b []byte) (n int, err error)
tryReadFull is like io.ReadFull except it returns io.EOF when it is hit
before len(b) bytes are read.
func validPAXRecord(k, v string) bool
validPAXRecord reports whether the key-value pair is valid where each record
is formatted as:
"%d %s=%s\n" % (size, key, value)
Keys and values should be UTF-8, but the number of bad writers out there
forces us to be a more liberal. Thus, we only reject all keys with NUL, and
only reject NULs in values for the PAX version of the USTAR string fields.
The key must not contain an '=' character.
func validateSparseEntries(sp []sparseEntry, size int64) bool
validateSparseEntries reports whether sp is a valid sparse map. It does not
matter whether sp represents data fragments or hole fragments.
TYPES
type FileInfoNames interface {
fs.FileInfo
Uname() (string, error)
Gname() (string, error)
}
FileInfoNames extends fs.FileInfo. Passing an instance of this to
FileInfoHeader permits the caller to avoid a system-dependent name lookup by
specifying the Uname and Gname directly.
type Format int
Format represents the tar archive format.
The original tar format was introduced in Unix V7. Since then, there have
been multiple competing formats attempting to standardize or extend the V7
format to overcome its limitations. The most common formats are the USTAR,
PAX, and GNU formats, each with their own advantages and limitations.
The following table captures the capabilities of each format:
| USTAR | PAX | GNU
------------------+--------+-----------+----------
Name | 256B | unlimited | unlimited
Linkname | 100B | unlimited | unlimited
Size | uint33 | unlimited | uint89
Mode | uint21 | uint21 | uint57
Uid/Gid | uint21 | unlimited | uint57
Uname/Gname | 32B | unlimited | 32B
ModTime | uint33 | unlimited | int89
AccessTime | n/a | unlimited | int89
ChangeTime | n/a | unlimited | int89
Devmajor/Devminor | uint21 | uint21 | uint57
------------------+--------+-----------+----------
string encoding | ASCII | UTF-8 | binary
sub-second times | no | yes | no
sparse files | no | yes | yes
The table's upper portion shows the Header fields, where each format reports
the maximum number of bytes allowed for each string field and the integer
type used to store each numeric field (where timestamps are stored as the
number of seconds since the Unix epoch).
The table's lower portion shows specialized features of each format,
such as supported string encodings, support for sub-second timestamps,
or support for sparse files.
The Writer currently provides no support for sparse files.
const (
FormatUnknown
formatV7
FormatUSTAR
FormatPAX
FormatGNU
formatSTAR
formatMax
)
Constants to identify various tar formats.
func (f Format) String() string
func (f Format) has(f2 Format) bool
func (f *Format) mayBe(f2 Format)
func (f *Format) mayOnlyBe(f2 Format)
func (f *Format) mustNotBe(f2 Format)
type Header struct {
Typeflag byte
Xattrs map[string]string
PAXRecords map[string]string
Format Format
}
A Header represents a single header in a tar archive. Some fields may not be
populated.
For forward compatibility, users that retrieve a Header from Reader.Next,
mutate it in some ways, and then pass it back to Writer.WriteHeader
should do so by creating a new Header and copying the fields that they are
interested in preserving.
func FileInfoHeader(fi fs.FileInfo, link string) (*Header, error)
FileInfoHeader creates a partially-populated Header from fi. If fi describes
a symlink, FileInfoHeader records link as the link target. If fi describes a
directory, a slash is appended to the name.
Since fs.FileInfo's Name method only returns the base name of the file it
describes, it may be necessary to modify Header.Name to provide the full
path name of the file.
If fi implements FileInfoNames Header.Gname and Header.Uname are provided by
the methods of the interface.
func (h *Header) FileInfo() fs.FileInfo
FileInfo returns an fs.FileInfo for the Header.
func (h Header) allowedFormats() (format Format, paxHdrs map[string]string, err error)
allowedFormats determines which formats can be used. The value returned is
the logical OR of multiple possible formats. If the value is FormatUnknown,
then the input Header cannot be encoded and an error is returned explaining
why.
As a by-product of checking the fields, this function returns paxHdrs, which
contain all fields that could not be directly encoded. A value receiver
ensures that this method does not mutate the source Header.
type Reader struct {
r io.Reader
err error
}
Reader provides sequential access to the contents of a tar archive.
Reader.Next advances to the next file in the archive (including the first),
and then Reader can be treated as an io.Reader to access the file's data.
func NewReader(r io.Reader) *Reader
NewReader creates a new Reader reading from r.
func (tr *Reader) Next() (*Header, error)
Next advances to the next entry in the tar archive. The Header.Size
determines how many bytes can be read for the next file. Any remaining data
in the current file is automatically discarded. At the end of the archive,
Next returns the error io.EOF.
If Next encounters a non-local name (as defined by filepath.IsLocal) and the
GODEBUG environment variable contains `tarinsecurepath=0`, Next returns the
header with an ErrInsecurePath error. A future version of Go may introduce
this behavior by default. Programs that want to accept non-local names can
ignore the ErrInsecurePath error and use the returned header.
func (tr *Reader) Read(b []byte) (int, error)
Read reads from the current file in the tar archive. It returns (0, io.EOF)
when it reaches the end of that file, until [Next] is called to advance to
the next file.
If the current file is sparse, then the regions marked as a hole are read
back as NUL-bytes.
Calling Read on special types like TypeLink, TypeSymlink, TypeChar,
TypeBlock, TypeDir, and TypeFifo returns (0, io.EOF) regardless of what the
[Header.Size] claims.
func (tr *Reader) handleRegularFile(hdr *Header) error
handleRegularFile sets up the current file reader and padding such that it
can only read the following logical data section. It will properly handle
special headers that contain no data section.
func (tr *Reader) handleSparseFile(hdr *Header, rawHdr *block) error
handleSparseFile checks if the current file is a sparse format of any type
and sets the curr reader appropriately.
func (tr *Reader) next() (*Header, error)
func (tr *Reader) readGNUSparsePAXHeaders(hdr *Header) (sparseDatas, error)
readGNUSparsePAXHeaders checks the PAX headers for GNU sparse headers.
If they are found, then this function reads the sparse map and returns it.
This assumes that 0.0 headers have already been converted to 0.1 headers by
the PAX header parsing logic.
func (tr *Reader) readHeader() (*Header, *block, error)
readHeader reads the next block header and assumes that the underlying
reader is already aligned to a block boundary. It returns the raw block of
the header in case further processing is required.
The err will be set to io.EOF only when one of the following occurs:
- Exactly 0 bytes are read and EOF is hit.
- Exactly 1 block of zeros is read and EOF is hit.
- At least 2 blocks of zeros are read.
func (tr *Reader) readOldGNUSparseMap(hdr *Header, blk *block) (sparseDatas, error)
readOldGNUSparseMap reads the sparse map from the old GNU sparse format.
The sparse map is stored in the tar header if it's small enough. If it's
larger than four entries, then one or more extension headers are used to
store the rest of the sparse map.
The Header.Size does not reflect the size of any extended headers used.
Thus, this function will read from the raw io.Reader to fetch extra headers.
This method mutates blk in the process.
func (tr *Reader) writeTo(w io.Writer) (int64, error)
writeTo writes the content of the current file to w. The bytes written
matches the number of remaining bytes in the current file.
If the current file is sparse and w is an io.WriteSeeker, then writeTo uses
Seek to skip past holes defined in Header.SparseHoles, assuming that skipped
regions are filled with NULs. This always writes the last byte to ensure w
is the right size.
TODO(dsnet): Re-export this when adding sparse file support. See
type Writer struct {
w io.Writer
err error
}
Writer provides sequential writing of a tar archive. Writer.WriteHeader
begins a new file with the provided Header, and then Writer can be treated
as an io.Writer to supply that file's data.
func NewWriter(w io.Writer) *Writer
NewWriter creates a new Writer writing to w.
func (tw *Writer) AddFS(fsys fs.FS) error
AddFS adds the files from fs.FS to the archive. It walks the directory tree
starting at the root of the filesystem adding each file to the tar archive
while maintaining the directory structure.
func (tw *Writer) Close() error
Close closes the tar archive by flushing the padding, and writing the
footer. If the current file (from a prior call to Writer.WriteHeader) is not
fully written, then this returns an error.
func (tw *Writer) Flush() error
Flush finishes writing the current file's block padding. The current file
must be fully written before Flush can be called.
This is unnecessary as the next call to Writer.WriteHeader or Writer.Close
will implicitly flush out the file's padding.
func (tw *Writer) Write(b []byte) (int, error)
Write writes to the current file in the tar archive. Write returns the
error ErrWriteTooLong if more than Header.Size bytes are written after
Writer.WriteHeader.
Calling Write on special types like TypeLink, TypeSymlink, TypeChar,
TypeBlock, TypeDir, and TypeFifo returns (0, ErrWriteTooLong) regardless of
what the [Header.Size] claims.
func (tw *Writer) WriteHeader(hdr *Header) error
WriteHeader writes hdr and prepares to accept the file's contents.
The Header.Size determines how many bytes can be written for the next file.
If the current file is not fully written, then this returns an error.
This implicitly flushes any padding necessary before writing the header.
func (tw *Writer) readFrom(r io.Reader) (int64, error)
readFrom populates the content of the current file by reading from r.
The bytes read must match the number of remaining bytes in the current file.
If the current file is sparse and r is an io.ReadSeeker, then readFrom uses
Seek to skip past holes defined in Header.SparseHoles, assuming that skipped
regions are all NULs. This always reads the last byte to ensure r is the
right size.
TODO(dsnet): Re-export this when adding sparse file support. See
func (tw *Writer) templateV7Plus(hdr *Header, fmtStr stringFormatter, fmtNum numberFormatter) *block
templateV7Plus fills out the V7 fields of a block using values from hdr.
It also fills out fields (uname, gname, devmajor, devminor) that are shared
in the USTAR, PAX, and GNU formats using the provided formatters.
The block returned is only valid until the next call to templateV7Plus or
writeRawFile.
func (tw *Writer) writeGNUHeader(hdr *Header) error
func (tw *Writer) writePAXHeader(hdr *Header, paxHdrs map[string]string) error
func (tw *Writer) writeRawFile(name, data string, flag byte, format Format) error
writeRawFile writes a minimal file with the given name and flag type. It
uses format to encode the header format and will write data as the body. It
uses default values for all of the other fields (as BSD and GNU tar does).
func (tw *Writer) writeRawHeader(blk *block, size int64, flag byte) error
writeRawHeader writes the value of blk, regardless of its value. It sets up
the Writer such that it can accept a file of the given size. If the flag is
a special header-only flag, then the size is treated as zero.
func (tw *Writer) writeUSTARHeader(hdr *Header) error
type block [blockSize]byte
var zeroBlock block
func (b *block) computeChecksum() (unsigned, signed int64)
computeChecksum computes the checksum for the header block. POSIX specifies
a sum of the unsigned byte values, but the Sun tar used signed byte values.
We compute and return both.
func (b *block) getFormat() Format
getFormat checks that the block is a valid tar header based on the checksum.
It then attempts to guess the specific format based on magic values.
If the checksum fails, then FormatUnknown is returned.
func (b *block) reset()
reset clears the block with all zeros.
func (b *block) setFormat(format Format)
setFormat writes the magic values necessary for specified format and then
updates the checksum accordingly.
func (b *block) toGNU() *headerGNU
func (b *block) toSTAR() *headerSTAR
func (b *block) toSparse() sparseArray
func (b *block) toUSTAR() *headerUSTAR
func (b *block) toV7() *headerV7
Convert block to any number of formats.
type fileReader interface {
io.Reader
fileState
WriteTo(io.Writer) (int64, error)
}
type fileState interface {
logicalRemaining() int64
physicalRemaining() int64
}
fileState tracks the number of logical (includes sparse holes) and physical
(actual in tar archive) bytes remaining for the current file.
Invariant: logicalRemaining >= physicalRemaining
type fileWriter interface {
io.Writer
fileState
ReadFrom(io.Reader) (int64, error)
}
type formatter struct {
}
func (f *formatter) formatNumeric(b []byte, x int64)
formatNumeric encodes x into b using base-8 (octal) encoding if possible.
Otherwise it will attempt to use base-256 (binary) encoding.
func (f *formatter) formatOctal(b []byte, x int64)
func (f *formatter) formatString(b []byte, s string)
formatString copies s into b, NUL-terminating if possible.
type headerError []string
func (he headerError) Error() string
type headerFileInfo struct {
h *Header
}
headerFileInfo implements fs.FileInfo.
func (fi headerFileInfo) IsDir() bool
func (fi headerFileInfo) ModTime() time.Time
func (fi headerFileInfo) Mode() (mode fs.FileMode)
Mode returns the permission and mode bits for the headerFileInfo.
func (fi headerFileInfo) Name() string
Name returns the base name of the file.
func (fi headerFileInfo) Size() int64
func (fi headerFileInfo) String() string
func (fi headerFileInfo) Sys() any
type headerGNU [blockSize]byte
func (h *headerGNU) accessTime() []byte
func (h *headerGNU) changeTime() []byte
func (h *headerGNU) devMajor() []byte
func (h *headerGNU) devMinor() []byte
func (h *headerGNU) groupName() []byte
func (h *headerGNU) magic() []byte
func (h *headerGNU) realSize() []byte
func (h *headerGNU) sparse() sparseArray
func (h *headerGNU) userName() []byte
func (h *headerGNU) v7() *headerV7
func (h *headerGNU) version() []byte
type headerSTAR [blockSize]byte
func (h *headerSTAR) accessTime() []byte
func (h *headerSTAR) changeTime() []byte
func (h *headerSTAR) devMajor() []byte
func (h *headerSTAR) devMinor() []byte
func (h *headerSTAR) groupName() []byte
func (h *headerSTAR) magic() []byte
func (h *headerSTAR) prefix() []byte
func (h *headerSTAR) trailer() []byte
func (h *headerSTAR) userName() []byte
func (h *headerSTAR) v7() *headerV7
func (h *headerSTAR) version() []byte
type headerUSTAR [blockSize]byte
func (h *headerUSTAR) devMajor() []byte
func (h *headerUSTAR) devMinor() []byte
func (h *headerUSTAR) groupName() []byte
func (h *headerUSTAR) magic() []byte
func (h *headerUSTAR) prefix() []byte
func (h *headerUSTAR) userName() []byte
func (h *headerUSTAR) v7() *headerV7
func (h *headerUSTAR) version() []byte
type headerV7 [blockSize]byte
func (h *headerV7) chksum() []byte
func (h *headerV7) gid() []byte
func (h *headerV7) linkName() []byte
func (h *headerV7) modTime() []byte
func (h *headerV7) mode() []byte
func (h *headerV7) name() []byte
func (h *headerV7) size() []byte
func (h *headerV7) typeFlag() []byte
func (h *headerV7) uid() []byte
type numberFormatter func([]byte, int64)
type parser struct {
}
func (p *parser) parseNumeric(b []byte) int64
parseNumeric parses the input as being encoded in either base-256 or octal.
This function may return negative numbers. If parsing fails or an integer
overflow occurs, err will be set.
func (p *parser) parseOctal(b []byte) int64
func (*parser) parseString(b []byte) string
parseString parses bytes as a NUL-terminated C-style string. If a NUL byte
is not found then the whole slice is returned as a string.
type regFileReader struct {
}
regFileReader is a fileReader for reading data from a regular file entry.
func (fr *regFileReader) Read(b []byte) (n int, err error)
func (fr *regFileReader) WriteTo(w io.Writer) (int64, error)
func (fr regFileReader) logicalRemaining() int64
logicalRemaining implements fileState.logicalRemaining.
func (fr regFileReader) physicalRemaining() int64
physicalRemaining implements fileState.physicalRemaining.
type regFileWriter struct {
}
regFileWriter is a fileWriter for writing data to a regular file entry.
func (fw *regFileWriter) ReadFrom(r io.Reader) (int64, error)
func (fw *regFileWriter) Write(b []byte) (n int, err error)
func (fw regFileWriter) logicalRemaining() int64
logicalRemaining implements fileState.logicalRemaining.
func (fw regFileWriter) physicalRemaining() int64
physicalRemaining implements fileState.physicalRemaining.
type sparseArray []byte
func (s sparseArray) entry(i int) sparseElem
func (s sparseArray) isExtended() []byte
func (s sparseArray) maxEntries() int
type sparseDatas []sparseEntry
A sparse file can be represented as either a sparseDatas or a sparseHoles.
As long as the total size is known, they are equivalent and one can be
converted to the other form and back. The various tar formats with sparse
file support represent sparse files in the sparseDatas form. That is,
they specify the fragments in the file that has data, and treat everything
else as having zero bytes. As such, the encoding and decoding logic in this
package deals with sparseDatas.
However, the external API uses sparseHoles instead of sparseDatas because
the zero value of sparseHoles logically represents a normal file (i.e.,
there are no holes in it). On the other hand, the zero value of sparseDatas
implies that the file has no data in it, which is rather odd.
As an example, if the underlying raw file contains the 10-byte data:
var compactFile = "abcdefgh"
And the sparse map has the following entries:
var spd sparseDatas = []sparseEntry{
}
var sph sparseHoles = []sparseEntry{
}
Then the content of the resulting sparse file with a Header.Size of 25 is:
var sparseFile = "\x00"*2 + "abcde" + "\x00"*11 + "fgh" + "\x00"*4
func readGNUSparseMap0x1(paxHdrs map[string]string) (sparseDatas, error)
readGNUSparseMap0x1 reads the sparse map as stored in GNU's PAX sparse
format version 0.1. The sparse map is stored in the PAX headers.
func readGNUSparseMap1x0(r io.Reader) (sparseDatas, error)
readGNUSparseMap1x0 reads the sparse map as stored in GNU's PAX sparse
format version 1.0. The format of the sparse map consists of a series of
newline-terminated numeric fields. The first field is the number of entries
and is always present. Following this are the entries, consisting of two
fields (offset, length). This function must stop reading at the end boundary
of the block containing the last newline.
Note that the GNU manual says that numeric values should be encoded in octal
format. However, the GNU tar utility itself outputs these values in decimal.
As such, this library treats values as being encoded in decimal.
type sparseElem []byte
func (s sparseElem) length() []byte
func (s sparseElem) offset() []byte
type sparseEntry struct{ Offset, Length int64 }
sparseEntry represents a Length-sized fragment at Offset in the file.
func alignSparseEntries(src []sparseEntry, size int64) []sparseEntry
alignSparseEntries mutates src and returns dst where each fragment's
starting offset is aligned up to the nearest block edge, and each ending
offset is aligned down to the nearest block edge.
Even though the Go tar Reader and the BSD tar utility can handle entries
with arbitrary offsets and lengths, the GNU tar utility can only handle
offsets and lengths that are multiples of blockSize.
func invertSparseEntries(src []sparseEntry, size int64) []sparseEntry
invertSparseEntries converts a sparse map from one form to the other.
If the input is sparseHoles, then it will output sparseDatas and vice-versa.
The input must have been already validated.
This function mutates src and returns a normalized map where:
- adjacent fragments are coalesced together
- only the last fragment may be empty
- the endOffset of the last fragment is the total size
func (s sparseEntry) endOffset() int64
type sparseFileReader struct {
}
sparseFileReader is a fileReader for reading data from a sparse file entry.
func (sr *sparseFileReader) Read(b []byte) (n int, err error)
func (sr *sparseFileReader) WriteTo(w io.Writer) (n int64, err error)
func (sr sparseFileReader) logicalRemaining() int64
func (sr sparseFileReader) physicalRemaining() int64
type sparseFileWriter struct {
}
sparseFileWriter is a fileWriter for writing data to a sparse file entry.
func (sw *sparseFileWriter) ReadFrom(r io.Reader) (n int64, err error)
func (sw *sparseFileWriter) Write(b []byte) (n int, err error)
func (sw sparseFileWriter) logicalRemaining() int64
func (sw sparseFileWriter) physicalRemaining() int64
type sparseHoles []sparseEntry
A sparse file can be represented as either a sparseDatas or a sparseHoles.
As long as the total size is known, they are equivalent and one can be
converted to the other form and back. The various tar formats with sparse
file support represent sparse files in the sparseDatas form. That is,
they specify the fragments in the file that has data, and treat everything
else as having zero bytes. As such, the encoding and decoding logic in this
package deals with sparseDatas.
However, the external API uses sparseHoles instead of sparseDatas because
the zero value of sparseHoles logically represents a normal file (i.e.,
there are no holes in it). On the other hand, the zero value of sparseDatas
implies that the file has no data in it, which is rather odd.
As an example, if the underlying raw file contains the 10-byte data:
var compactFile = "abcdefgh"
And the sparse map has the following entries:
var spd sparseDatas = []sparseEntry{
}
var sph sparseHoles = []sparseEntry{
}
Then the content of the resulting sparse file with a Header.Size of 25 is:
var sparseFile = "\x00"*2 + "abcde" + "\x00"*11 + "fgh" + "\x00"*4
type stringFormatter func([]byte, string)
type zeroReader struct{}
func (zeroReader) Read(b []byte) (int, error)
type zeroWriter struct{}
zeroWriter may only be written with NULs, otherwise it returns errWriteHole.
func (zeroWriter) Write(b []byte) (int, error)
archive/zip
func RegisterCompressor(method uint16, comp Compressor)
RegisterCompressor registers custom compressors for a specified method ID.
The common methods Store and Deflate are built in.
func RegisterDecompressor(method uint16, dcomp Decompressor)
RegisterDecompressor allows custom decompressors for a specified method ID.
The common methods Store and Deflate are built in.
func detectUTF8(s string) (valid, require bool)
detectUTF8 reports whether s is a valid UTF-8 string, and whether the string
must be considered UTF-8 encoding (i.e., not compatible with CP-437, ASCII,
or any other common encoding).
func fileEntryCompare(x, y string) int
func fileModeToUnixMode(mode fs.FileMode) uint32
func findDirectory64End(r io.ReaderAt, directoryEndOffset int64) (int64, error)
findDirectory64End tries to read the zip64 locator just before the directory
end and returns the offset of the zip64 directory end if found.
func findSignatureInBlock(b []byte) int
func init()
func msDosTimeToTime(dosDate, dosTime uint16) time.Time
msDosTimeToTime converts an MS-DOS date and time
into a time.Time. The resolution is 2s. See:
func msdosModeToFileMode(m uint32) (mode fs.FileMode)
func newFlateReader(r io.Reader) io.ReadCloser
func newFlateWriter(w io.Writer) io.WriteCloser
func readDataDescriptor(r io.Reader, f *File) error
func readDirectory64End(r io.ReaderAt, offset int64, d *directoryEnd) (err error)
readDirectory64End reads the zip64 directory end and updates the directory
end with the zip64 directory end values.
func readDirectoryHeader(f *File, r io.Reader) error
readDirectoryHeader attempts to read a directory header from r. It returns
io.ErrUnexpectedEOF if it cannot read a complete header, and ErrFormat if it
doesn't find a valid header signature.
func split(name string) (dir, elem string, isDir bool)
func timeToMsDosTime(t time.Time) (fDate uint16, fTime uint16)
timeToMsDosTime converts a time.Time to an
MS-DOS date and time. The resolution is 2s. See:
func timeZone(offset time.Duration) *time.Location
timeZone returns a *time.Location based on the provided offset. If the
offset is non-sensible, then this uses an offset of zero.
func toValidName(name string) string
toValidName coerces name to be a valid name for fs.FS.Open.
func unixModeToFileMode(m uint32) fs.FileMode
func writeHeader(w io.Writer, h *header) error
TYPES
type Compressor func(w io.Writer) (io.WriteCloser, error)
A Compressor returns a new compressing writer, writing to w.
The WriteCloser's Close method must be used to flush pending data to w.
The Compressor itself must be safe to invoke from multiple goroutines
simultaneously, but each returned writer will be used only by one goroutine
at a time.
func compressor(method uint16) Compressor
type Decompressor func(r io.Reader) io.ReadCloser
A Decompressor returns a new decompressing reader, reading from r. The
io.ReadCloser's Close method must be used to release associated resources.
The Decompressor itself must be safe to invoke from multiple goroutines
simultaneously, but each returned reader will be used only by one goroutine
at a time.
func decompressor(method uint16) Decompressor
type File struct {
FileHeader
zip *Reader
zipr io.ReaderAt
}
A File is a single file in a ZIP archive. The file information is in the
embedded FileHeader. The file content can be accessed by calling File.Open.
func (f *File) DataOffset() (offset int64, err error)
DataOffset returns the offset of the file's possibly-compressed data,
relative to the beginning of the zip file.
Most callers should instead use File.Open, which transparently decompresses
data and verifies checksums.
func (f *File) Open() (io.ReadCloser, error)
Open returns a ReadCloser that provides access to the File's contents.
Multiple files may be read concurrently.
func (f *File) OpenRaw() (io.Reader, error)
OpenRaw returns a Reader that provides access to the File's contents without
decompression.
func (f *File) findBodyOffset() (int64, error)
findBodyOffset does the minimum work to verify the file has a header and
returns the file body offset.
type FileHeader struct {
Name string
Comment string
NonUTF8 bool
CreatorVersion uint16
ReaderVersion uint16
Flags uint16
Method uint16
Modified time.Time
ModifiedTime uint16
ModifiedDate uint16
CRC32 uint32
CompressedSize uint32
UncompressedSize uint32
CompressedSize64 uint64
UncompressedSize64 uint64
Extra []byte
}
FileHeader describes a file within a ZIP file. See the ZIP specification for
details.
func FileInfoHeader(fi fs.FileInfo) (*FileHeader, error)
FileInfoHeader creates a partially-populated FileHeader from an fs.FileInfo.
Because fs.FileInfo's Name method returns only the base name of the file
it describes, it may be necessary to modify the Name field of the returned
header to provide the full path name of the file. If compression is desired,
callers should set the FileHeader.Method field; it is unset by default.
func (h *FileHeader) FileInfo() fs.FileInfo
FileInfo returns an fs.FileInfo for the FileHeader.
func (h *FileHeader) ModTime() time.Time
ModTime returns the modification time in UTC using the legacy [ModifiedDate]
and [ModifiedTime] fields.
Deprecated: Use [Modified] instead.
func (h *FileHeader) Mode() (mode fs.FileMode)
Mode returns the permission and mode bits for the FileHeader.
func (h *FileHeader) SetModTime(t time.Time)
SetModTime sets the [Modified], [ModifiedTime], and [ModifiedDate] fields to
the given time in UTC.
Deprecated: Use [Modified] instead.
func (h *FileHeader) SetMode(mode fs.FileMode)
SetMode changes the permission and mode bits for the FileHeader.
func (h *FileHeader) hasDataDescriptor() bool
func (h *FileHeader) isZip64() bool
isZip64 reports whether the file size exceeds the 32 bit limit
type ReadCloser struct {
f *os.File
Reader
}
A ReadCloser is a Reader that must be closed when no longer needed.
func OpenReader(name string) (*ReadCloser, error)
OpenReader will open the Zip file specified by name and return a ReadCloser.
If any file inside the archive uses a non-local name (as defined by
filepath.IsLocal) or a name containing backslashes and the GODEBUG
environment variable contains `zipinsecurepath=0`, OpenReader returns the
reader with an ErrInsecurePath error. A future version of Go may introduce
this behavior by default. Programs that want to accept non-local names can
ignore the ErrInsecurePath error and use the returned reader.
func (rc *ReadCloser) Close() error
Close closes the Zip file, rendering it unusable for I/O.
type Reader struct {
r io.ReaderAt
File []*File
Comment string
decompressors map[uint16]Decompressor
baseOffset int64
fileListOnce sync.Once
fileList []fileListEntry
}
A Reader serves content from a ZIP archive.
func NewReader(r io.ReaderAt, size int64) (*Reader, error)
NewReader returns a new Reader reading from r, which is assumed to have the
given size in bytes.
If any file inside the archive uses a non-local name (as defined by
filepath.IsLocal) or a name containing backslashes and the GODEBUG
environment variable contains `zipinsecurepath=0`, NewReader returns the
reader with an ErrInsecurePath error. A future version of Go may introduce
this behavior by default. Programs that want to accept non-local names can
ignore the ErrInsecurePath error and use the returned reader.
func (r *Reader) Open(name string) (fs.File, error)
Open opens the named file in the ZIP archive, using the semantics of
fs.FS.Open: paths are always slash separated, with no leading / or ../
elements.
func (r *Reader) RegisterDecompressor(method uint16, dcomp Decompressor)
RegisterDecompressor registers or overrides a custom decompressor for a
specific method ID. If a decompressor for a given method is not found,
Reader will default to looking up the decompressor at the package level.
func (r *Reader) decompressor(method uint16) Decompressor
func (r *Reader) init(rdr io.ReaderAt, size int64) error
func (r *Reader) initFileList()
func (r *Reader) openLookup(name string) *fileListEntry
func (r *Reader) openReadDir(dir string) []fileListEntry
type Writer struct {
cw *countWriter
dir []*header
last *fileWriter
closed bool
compressors map[uint16]Compressor
comment string
testHookCloseSizeOffset func(size, offset uint64)
}
Writer implements a zip file writer.
func NewWriter(w io.Writer) *Writer
NewWriter returns a new Writer writing a zip file to w.
func (w *Writer) AddFS(fsys fs.FS) error
AddFS adds the files from fs.FS to the archive. It walks the directory tree
starting at the root of the filesystem adding each file to the zip using
deflate while maintaining the directory structure.
func (w *Writer) Close() error
Close finishes writing the zip file by writing the central directory.
It does not close the underlying writer.
func (w *Writer) Copy(f *File) error
Copy copies the file f (obtained from a Reader) into w. It copies the raw
form directly bypassing decompression, compression, and validation.
func (w *Writer) Create(name string) (io.Writer, error)
Create adds a file to the zip file using the provided name. It returns a
Writer to which the file contents should be written. The file contents will
be compressed using the Deflate method. The name must be a relative path:
it must not start with a drive letter (e.g. C:) or leading slash, and only
forward slashes are allowed. To create a directory instead of a file,
add a trailing slash to the name. Duplicate names will not overwrite
previous entries and are appended to the zip file. The file's contents
must be written to the io.Writer before the next call to Writer.Create,
Writer.CreateHeader, or Writer.Close.
func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error)
CreateHeader adds a file to the zip archive using the provided FileHeader
for the file metadata. Writer takes ownership of fh and may mutate its
fields. The caller must not modify fh after calling Writer.CreateHeader.
This returns a Writer to which the file contents should be written.
The file's contents must be written to the io.Writer before the next call to
Writer.Create, Writer.CreateHeader, Writer.CreateRaw, or Writer.Close.
func (w *Writer) CreateRaw(fh *FileHeader) (io.Writer, error)
CreateRaw adds a file to the zip archive using the provided FileHeader
and returns a Writer to which the file contents should be written.
The file's contents must be written to the io.Writer before the next call to
Writer.Create, Writer.CreateHeader, Writer.CreateRaw, or Writer.Close.
In contrast to Writer.CreateHeader, the bytes passed to Writer are not
compressed.
CreateRaw's argument is stored in w. If the argument is a pointer to the
embedded FileHeader in a File obtained from a Reader created from in-memory
data, then w will refer to all of that memory.
func (w *Writer) Flush() error
Flush flushes any buffered data to the underlying writer. Calling Flush is
not normally necessary; calling Close is sufficient.
func (w *Writer) RegisterCompressor(method uint16, comp Compressor)
RegisterCompressor registers or overrides a custom compressor for a specific
method ID. If a compressor for a given method is not found, Writer will
default to looking up the compressor at the package level.
func (w *Writer) SetComment(comment string) error
SetComment sets the end-of-central-directory comment field. It can only be
called before Writer.Close.
func (w *Writer) SetOffset(n int64)
SetOffset sets the offset of the beginning of the zip data within the
underlying writer. It should be used when the zip data is appended to an
existing file, such as a binary executable. It must be called before any
data is written.
func (w *Writer) compressor(method uint16) Compressor
func (w *Writer) prepare(fh *FileHeader) error
prepare performs the bookkeeping operations required at the start of
CreateHeader and CreateRaw.
type checksumReader struct {
rc io.ReadCloser
hash hash.Hash32
f *File
}
func (r *checksumReader) Close() error
func (r *checksumReader) Read(b []byte) (n int, err error)
func (r *checksumReader) Stat() (fs.FileInfo, error)
type countWriter struct {
w io.Writer
count int64
}
func (w *countWriter) Write(p []byte) (int, error)
type dirReader struct {
err error
}
func (r *dirReader) Close() error
func (r *dirReader) Read([]byte) (int, error)
type dirWriter struct{}
func (dirWriter) Write(b []byte) (int, error)
type directoryEnd struct {
directoryRecords uint64
directorySize uint64
commentLen uint16
comment string
}
func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, baseOffset int64, err error)
type fileInfoDirEntry interface {
fs.FileInfo
fs.DirEntry
}
type fileListEntry struct {
name string
file *File
isDir bool
isDup bool
}
A fileListEntry is a File and its ename. If file == nil, the fileListEntry
describes a directory without metadata.
func (f *fileListEntry) Info() (fs.FileInfo, error)
func (f *fileListEntry) IsDir() bool
func (f *fileListEntry) ModTime() time.Time
func (f *fileListEntry) Mode() fs.FileMode
func (f *fileListEntry) Name() string
Only used for directories.
func (f *fileListEntry) Size() int64
func (f *fileListEntry) String() string
func (f *fileListEntry) Sys() any
func (f *fileListEntry) Type() fs.FileMode
func (f *fileListEntry) stat() (fileInfoDirEntry, error)
type fileWriter struct {
*header
zipw io.Writer
rawCount *countWriter
comp io.WriteCloser
compCount *countWriter
crc32 hash.Hash32
closed bool
}
func (w *fileWriter) Write(p []byte) (int, error)
func (w *fileWriter) close() error
func (w *fileWriter) writeDataDescriptor() error
type header struct {
*FileHeader
offset uint64
raw bool
}
type headerFileInfo struct {
fh *FileHeader
}
headerFileInfo implements fs.FileInfo.
func (fi headerFileInfo) Info() (fs.FileInfo, error)
func (fi headerFileInfo) IsDir() bool
func (fi headerFileInfo) ModTime() time.Time
func (fi headerFileInfo) Mode() fs.FileMode
func (fi headerFileInfo) Name() string
func (fi headerFileInfo) Size() int64
func (fi headerFileInfo) String() string
func (fi headerFileInfo) Sys() any
func (fi headerFileInfo) Type() fs.FileMode
type nopCloser struct {
io.Writer
}
func (w nopCloser) Close() error
type openDir struct {
e *fileListEntry
files []fileListEntry
offset int
}
func (d *openDir) Close() error
func (d *openDir) Read([]byte) (int, error)
func (d *openDir) ReadDir(count int) ([]fs.DirEntry, error)
func (d *openDir) Stat() (fs.FileInfo, error)
type pooledFlateReader struct {
fr io.ReadCloser
}
func (r *pooledFlateReader) Close() error
func (r *pooledFlateReader) Read(p []byte) (n int, err error)
type pooledFlateWriter struct {
fw *flate.Writer
}
func (w *pooledFlateWriter) Close() error
func (w *pooledFlateWriter) Write(p []byte) (n int, err error)
type readBuf []byte
func (b *readBuf) sub(n int) readBuf
func (b *readBuf) uint16() uint16
func (b *readBuf) uint32() uint32
func (b *readBuf) uint64() uint64
func (b *readBuf) uint8() uint8
type writeBuf []byte
func (b *writeBuf) uint16(v uint16)
func (b *writeBuf) uint32(v uint32)
func (b *writeBuf) uint64(v uint64)
func (b *writeBuf) uint8(v uint8)
bufio
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)
ScanBytes is a split function for a Scanner that returns each byte as a
token.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)
ScanLines is a split function for a Scanner that returns each line of text,
stripped of any trailing end-of-line marker. The returned line may be empty.
The end-of-line marker is one optional carriage return followed by one
mandatory newline. In regular expression notation, it is `\r?\n`. The last
non-empty line of input will be returned even if it has no newline.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error)
ScanRunes is a split function for a Scanner that returns each UTF-8-encoded
rune as a token. The sequence of runes returned is equivalent to that
from a range loop over the input as a string, which means that erroneous
UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd". Because of the Scan
interface, this makes it impossible for the client to distinguish correctly
encoded replacement runes from encoding errors.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error)
ScanWords is a split function for a Scanner that returns each
space-separated word of text, with surrounding spaces deleted. It will never
return an empty string. The definition of space is set by unicode.IsSpace.
func dropCR(data []byte) []byte
dropCR drops a terminal \r from the data.
func isSpace(r rune) bool
isSpace reports whether the character is a Unicode white space character.
We avoid dependency on the unicode package, but check validity of the
implementation in the tests.
TYPES
type ReadWriter struct {
*Reader
*Writer
}
ReadWriter stores pointers to a Reader and a Writer. It implements
io.ReadWriter.
func NewReadWriter(r *Reader, w *Writer) *ReadWriter
NewReadWriter allocates a new ReadWriter that dispatches to r and w.
type Reader struct {
buf []byte
err error
}
Reader implements buffering for an io.Reader object. A new Reader is created
by calling NewReader or NewReaderSize; alternatively the zero value of a
Reader may be used after calling [Reset] on it.
func NewReader(rd io.Reader) *Reader
NewReader returns a new Reader whose buffer has the default size.
func NewReaderSize(rd io.Reader, size int) *Reader
NewReaderSize returns a new Reader whose buffer has at least the specified
size. If the argument io.Reader is already a Reader with large enough size,
it returns the underlying Reader.
func (b *Reader) Buffered() int
Buffered returns the number of bytes that can be read from the current
buffer.
func (b *Reader) Discard(n int) (discarded int, err error)
Discard skips the next n bytes, returning the number of bytes discarded.
If Discard skips fewer than n bytes, it also returns an error. If 0 <= n
<= b.Buffered(), Discard is guaranteed to succeed without reading from the
underlying io.Reader.
func (b *Reader) Peek(n int) ([]byte, error)
Peek returns the next n bytes without advancing the reader. The bytes stop
being valid at the next read call. If necessary, Peek will read more bytes
into the buffer in order to make n bytes available. If Peek returns fewer
than n bytes, it also returns an error explaining why the read is short.
The error is ErrBufferFull if n is larger than b's buffer size.
Calling Peek prevents a Reader.UnreadByte or Reader.UnreadRune call from
succeeding until the next read operation.
func (b *Reader) Read(p []byte) (n int, err error)
Read reads data into p. It returns the number of bytes read into p.
The bytes are taken from at most one Read on the underlying Reader, hence n
may be less than len(p). To read exactly len(p) bytes, use io.ReadFull(b,
p). If the underlying Reader can return a non-zero count with io.EOF,
then this Read method can do so as well; see the io.Reader docs.
func (b *Reader) ReadByte() (byte, error)
ReadByte reads and returns a single byte. If no byte is available, returns
an error.
func (b *Reader) ReadBytes(delim byte) ([]byte, error)
ReadBytes reads until the first occurrence of delim in the input,
returning a slice containing the data up to and including the delimiter.
If ReadBytes encounters an error before finding a delimiter, it returns the
data read before the error and the error itself (often io.EOF). ReadBytes
returns err != nil if and only if the returned data does not end in delim.
For simple uses, a Scanner may be more convenient.
func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)
ReadLine is a low-level line-reading primitive. Most callers should use
Reader.ReadBytes('\n') or Reader.ReadString('\n') instead or use a Scanner.
ReadLine tries to return a single line, not including the end-of-line bytes.
If the line was too long for the buffer then isPrefix is set and the
beginning of the line is returned. The rest of the line will be returned
from future calls. isPrefix will be false when returning the last fragment
of the line. The returned buffer is only valid until the next call to
ReadLine. ReadLine either returns a non-nil line or it returns an error,
never both.
The text returned from ReadLine does not include the line end ("\r\n" or
"\n"). No indication or error is given if the input ends without a final
line end. Calling Reader.UnreadByte after ReadLine will always unread the
last byte read (possibly a character belonging to the line end) even if that
byte is not part of the line returned by ReadLine.
func (b *Reader) ReadRune() (r rune, size int, err error)
ReadRune reads a single UTF-8 encoded Unicode character and returns the rune
and its size in bytes. If the encoded rune is invalid, it consumes one byte
and returns unicode.ReplacementChar (U+FFFD) with a size of 1.
func (b *Reader) ReadSlice(delim byte) (line []byte, err error)
ReadSlice reads until the first occurrence of delim in the input, returning
a slice pointing at the bytes in the buffer. The bytes stop being valid at
the next read. If ReadSlice encounters an error before finding a delimiter,
it returns all the data in the buffer and the error itself (often io.EOF).
ReadSlice fails with error ErrBufferFull if the buffer fills without a
delim. Because the data returned from ReadSlice will be overwritten by the
next I/O operation, most clients should use Reader.ReadBytes or ReadString
instead. ReadSlice returns err != nil if and only if line does not end in
delim.
func (b *Reader) ReadString(delim byte) (string, error)
ReadString reads until the first occurrence of delim in the input,
returning a string containing the data up to and including the delimiter.
If ReadString encounters an error before finding a delimiter, it returns the
data read before the error and the error itself (often io.EOF). ReadString
returns err != nil if and only if the returned data does not end in delim.
For simple uses, a Scanner may be more convenient.
func (b *Reader) Reset(r io.Reader)
Reset discards any buffered data, resets all state, and switches the
buffered reader to read from r. Calling Reset on the zero value of Reader
initializes the internal buffer to the default size. Calling b.Reset(b)
(that is, resetting a Reader to itself) does nothing.
func (b *Reader) Size() int
Size returns the size of the underlying buffer in bytes.
func (b *Reader) UnreadByte() error
UnreadByte unreads the last byte. Only the most recently read byte can be
unread.
UnreadByte returns an error if the most recent method called on the
Reader was not a read operation. Notably, Reader.Peek, Reader.Discard,
and Reader.WriteTo are not considered read operations.
func (b *Reader) UnreadRune() error
UnreadRune unreads the last rune. If the most recent method called on the
Reader was not a Reader.ReadRune, Reader.UnreadRune returns an error.
(In this regard it is stricter than Reader.UnreadByte, which will unread the
last byte from any read operation.)
func (b *Reader) WriteTo(w io.Writer) (n int64, err error)
WriteTo implements io.WriterTo. This may make multiple calls to the
Reader.Read method of the underlying Reader. If the underlying reader
supports the Reader.WriteTo method, this calls the underlying Reader.WriteTo
without buffering.
func (b *Reader) collectFragments(delim byte) (fullBuffers [][]byte, finalFragment []byte, totalLen int, err error)
collectFragments reads until the first occurrence of delim in the input.
It returns (slice of full buffers, remaining bytes before delim, total
number of bytes in the combined first two elements, error). The complete
result is equal to `bytes.Join(append(fullBuffers, finalFragment), nil)`,
which has a length of `totalLen`. The result is structured in this way to
allow callers to minimize allocations and copies.
func (b *Reader) fill()
fill reads a new chunk into the buffer.
func (b *Reader) readErr() error
func (b *Reader) reset(buf []byte, r io.Reader)
func (b *Reader) writeBuf(w io.Writer) (int64, error)
writeBuf writes the Reader's buffer to the writer.
type Scanner struct {
}
Scanner provides a convenient interface for reading data such as a file
of newline-delimited lines of text. Successive calls to the Scanner.Scan
method will step through the 'tokens' of a file, skipping the bytes between
the tokens. The specification of a token is defined by a split function
of type SplitFunc; the default split function breaks the input into lines
with line termination stripped. Scanner.Split functions are defined in
this package for scanning a file into lines, bytes, UTF-8-encoded runes,
and space-delimited words. The client may instead provide a custom split
function.
Scanning stops unrecoverably at EOF, the first I/O error, or a token too
large to fit in the Scanner.Buffer. When a scan stops, the reader may
have advanced arbitrarily far past the last token. Programs that need more
control over error handling or large tokens, or must run sequential scans on
a reader, should use bufio.Reader instead.
func NewScanner(r io.Reader) *Scanner
NewScanner returns a new Scanner to read from r. The split function defaults
to ScanLines.
func (s *Scanner) Buffer(buf []byte, max int)
Buffer sets the initial buffer to use when scanning and the maximum size of
buffer that may be allocated during scanning. The maximum token size must be
less than the larger of max and cap(buf). If max <= cap(buf), Scanner.Scan
will use this buffer only and do no allocation.
By default, Scanner.Scan uses an internal buffer and sets the maximum token
size to MaxScanTokenSize.
Buffer panics if it is called after scanning has started.
func (s *Scanner) Bytes() []byte
Bytes returns the most recent token generated by a call to Scanner.Scan. The
underlying array may point to data that will be overwritten by a subsequent
call to Scan. It does no allocation.
func (s *Scanner) Err() error
Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Scan() bool
Scan advances the Scanner to the next token, which will then be available
through the Scanner.Bytes or Scanner.Text method. It returns false when
there are no more tokens, either by reaching the end of the input or
an error. After Scan returns false, the Scanner.Err method will return
any error that occurred during scanning, except that if it was io.EOF,
Scanner.Err will return nil. Scan panics if the split function returns too
many empty tokens without advancing the input. This is a common error mode
for scanners.
func (s *Scanner) Split(split SplitFunc)
Split sets the split function for the Scanner. The default split function is
ScanLines.
Split panics if it is called after scanning has started.
func (s *Scanner) Text() string
Text returns the most recent token generated by a call to Scanner.Scan as a
newly allocated string holding its bytes.
func (s *Scanner) advance(n int) bool
advance consumes n bytes of the buffer. It reports whether the advance was
legal.
func (s *Scanner) setErr(err error)
setErr records the first error encountered.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)
SplitFunc is the signature of the split function used to tokenize the input.
The arguments are an initial substring of the remaining unprocessed data and
a flag, atEOF, that reports whether the Reader has no more data to give.
The return values are the number of bytes to advance the input and the next
token to return to the user, if any, plus an error, if any.
Scanning stops if the function returns an error, in which case some of the
input may be discarded. If that error is ErrFinalToken, scanning stops with
no error. A non-nil token delivered with ErrFinalToken will be the last
token, and a nil token with ErrFinalToken immediately stops the scanning.
Otherwise, the Scanner advances the input. If the token is not nil,
the Scanner returns it to the user. If the token is nil, the Scanner reads
more data and continues scanning; if there is no more data--if atEOF was
true--the Scanner returns. If the data does not yet hold a complete token,
for instance if it has no newline while scanning lines, a SplitFunc can
return (0, nil, nil) to signal the Scanner to read more data into the slice
and try again with a longer slice starting at the same point in the input.
The function is never called with an empty data slice unless atEOF is true.
If atEOF is true, however, data may be non-empty and, as always, holds
unprocessed text.
type Writer struct {
err error
buf []byte
n int
wr io.Writer
}
Writer implements buffering for an io.Writer object. If an error occurs
writing to a Writer, no more data will be accepted and all subsequent
writes, and Writer.Flush, will return the error. After all data has been
written, the client should call the Writer.Flush method to guarantee all
data has been forwarded to the underlying io.Writer.
func NewWriter(w io.Writer) *Writer
NewWriter returns a new Writer whose buffer has the default size.
If the argument io.Writer is already a Writer with large enough buffer size,
it returns the underlying Writer.
func NewWriterSize(w io.Writer, size int) *Writer
NewWriterSize returns a new Writer whose buffer has at least the specified
size. If the argument io.Writer is already a Writer with large enough size,
it returns the underlying Writer.
func (b *Writer) Available() int
Available returns how many bytes are unused in the buffer.
func (b *Writer) AvailableBuffer() []byte
AvailableBuffer returns an empty buffer with b.Available() capacity. This
buffer is intended to be appended to and passed to an immediately succeeding
Writer.Write call. The buffer is only valid until the next write operation
on b.
func (b *Writer) Buffered() int
Buffered returns the number of bytes that have been written into the current
buffer.
func (b *Writer) Flush() error
Flush writes any buffered data to the underlying io.Writer.
func (b *Writer) ReadFrom(r io.Reader) (n int64, err error)
ReadFrom implements io.ReaderFrom. If the underlying writer supports the
ReadFrom method, this calls the underlying ReadFrom. If there is buffered
data and an underlying ReadFrom, this fills the buffer and writes it before
calling ReadFrom.
func (b *Writer) Reset(w io.Writer)
Reset discards any unflushed buffered data, clears any error, and resets
b to write its output to w. Calling Reset on the zero value of Writer
initializes the internal buffer to the default size. Calling w.Reset(w)
(that is, resetting a Writer to itself) does nothing.
func (b *Writer) Size() int
Size returns the size of the underlying buffer in bytes.
func (b *Writer) Write(p []byte) (nn int, err error)
Write writes the contents of p into the buffer. It returns the number of
bytes written. If nn < len(p), it also returns an error explaining why the
write is short.
func (b *Writer) WriteByte(c byte) error
WriteByte writes a single byte.
func (b *Writer) WriteRune(r rune) (size int, err error)
WriteRune writes a single Unicode code point, returning the number of bytes
written and any error.
func (b *Writer) WriteString(s string) (int, error)
WriteString writes a string. It returns the number of bytes written. If the
count is less than len(s), it also returns an error explaining why the write
is short.
bytes
func Clone(b []byte) []byte
Clone returns a copy of b[:len(b)]. The result may have additional unused
capacity. Clone(nil) returns nil.
func Compare(a, b []byte) int
Compare returns an integer comparing two byte slices lexicographically.
The result will be 0 if a == b, -1 if a < b, and +1 if a > b. A nil argument
is equivalent to an empty slice.
func Contains(b, subslice []byte) bool
Contains reports whether subslice is within b.
func ContainsAny(b []byte, chars string) bool
ContainsAny reports whether any of the UTF-8-encoded code points in chars
are within b.
func ContainsFunc(b []byte, f func(rune) bool) bool
ContainsFunc reports whether any of the UTF-8-encoded code points r within b
satisfy f(r).
func ContainsRune(b []byte, r rune) bool
ContainsRune reports whether the rune is contained in the UTF-8-encoded byte
slice b.
func Count(s, sep []byte) int
Count counts the number of non-overlapping instances of sep in s. If sep is
an empty slice, Count returns 1 + the number of UTF-8-encoded code points in
s.
func Cut(s, sep []byte) (before, after []byte, found bool)
Cut slices s around the first instance of sep, returning the text before and
after sep. The found result reports whether sep appears in s. If sep does
not appear in s, cut returns s, nil, false.
Cut returns slices of the original slice s, not copies.
func CutPrefix(s, prefix []byte) (after []byte, found bool)
CutPrefix returns s without the provided leading prefix byte slice and
reports whether it found the prefix. If s doesn't start with prefix,
CutPrefix returns s, false. If prefix is the empty byte slice, CutPrefix
returns s, true.
CutPrefix returns slices of the original slice s, not copies.
func CutSuffix(s, suffix []byte) (before []byte, found bool)
CutSuffix returns s without the provided ending suffix byte slice and
reports whether it found the suffix. If s doesn't end with suffix, CutSuffix
returns s, false. If suffix is the empty byte slice, CutSuffix returns s,
true.
CutSuffix returns slices of the original slice s, not copies.
func Equal(a, b []byte) bool
Equal reports whether a and b are the same length and contain the same
bytes. A nil argument is equivalent to an empty slice.
func EqualFold(s, t []byte) bool
EqualFold reports whether s and t, interpreted as UTF-8 strings,
are equal under simple Unicode case-folding, which is a more general form of
case-insensitivity.
func Fields(s []byte) [][]byte
Fields interprets s as a sequence of UTF-8-encoded code points. It splits
the slice s around each instance of one or more consecutive white space
characters, as defined by unicode.IsSpace, returning a slice of subslices of
s or an empty slice if s contains only white space.
func FieldsFunc(s []byte, f func(rune) bool) [][]byte
FieldsFunc interprets s as a sequence of UTF-8-encoded code points.
It splits the slice s at each run of code points c satisfying f(c) and
returns a slice of subslices of s. If all code points in s satisfy f(c),
or len(s) == 0, an empty slice is returned.
FieldsFunc makes no guarantees about the order in which it calls f(c) and
assumes that f always returns the same value for a given c.
func FieldsFuncSeq(s []byte, f func(rune) bool) iter.Seq[[]byte]
FieldsFuncSeq returns an iterator over substrings of s split around runs of
Unicode code points satisfying f(c). The iterator yields the same strings
that would be returned by FieldsFunc(s), but without constructing the slice.
func FieldsSeq(s []byte) iter.Seq[[]byte]
FieldsSeq returns an iterator over substrings of s split around runs
of whitespace characters, as defined by unicode.IsSpace. The iterator
yields the same strings that would be returned by Fields(s), but without
constructing the slice.
func HasPrefix(s, prefix []byte) bool
HasPrefix reports whether the byte slice s begins with prefix.
func HasSuffix(s, suffix []byte) bool
HasSuffix reports whether the byte slice s ends with suffix.
func Index(s, sep []byte) int
Index returns the index of the first instance of sep in s, or -1 if sep is
not present in s.
func IndexAny(s []byte, chars string) int
IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points.
It returns the byte index of the first occurrence in s of any of the Unicode
code points in chars. It returns -1 if chars is empty or if there is no code
point in common.
func IndexByte(b []byte, c byte) int
IndexByte returns the index of the first instance of c in b, or -1 if c is
not present in b.
func IndexFunc(s []byte, f func(r rune) bool) int
IndexFunc interprets s as a sequence of UTF-8-encoded code points. It
returns the byte index in s of the first Unicode code point satisfying f(c),
or -1 if none do.
func IndexRune(s []byte, r rune) int
IndexRune interprets s as a sequence of UTF-8-encoded code points.
It returns the byte index of the first occurrence in s of the given rune.
It returns -1 if rune is not present in s. If r is utf8.RuneError,
it returns the first instance of any invalid UTF-8 byte sequence.
func Join(s [][]byte, sep []byte) []byte
Join concatenates the elements of s to create a new byte slice. The
separator sep is placed between elements in the resulting slice.
func LastIndex(s, sep []byte) int
LastIndex returns the index of the last instance of sep in s, or -1 if sep
is not present in s.
func LastIndexAny(s []byte, chars string) int
LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code
points. It returns the byte index of the last occurrence in s of any of the
Unicode code points in chars. It returns -1 if chars is empty or if there is
no code point in common.
func LastIndexByte(s []byte, c byte) int
LastIndexByte returns the index of the last instance of c in s, or -1 if c
is not present in s.
func LastIndexFunc(s []byte, f func(r rune) bool) int
LastIndexFunc interprets s as a sequence of UTF-8-encoded code points. It
returns the byte index in s of the last Unicode code point satisfying f(c),
or -1 if none do.
func Lines(s []byte) iter.Seq[[]byte]
Lines returns an iterator over the newline-terminated lines in the byte
slice s. The lines yielded by the iterator include their terminating
newlines. If s is empty, the iterator yields no lines at all. If s does
not end in a newline, the final yielded line will not end in a newline.
It returns a single-use iterator.
func Map(mapping func(r rune) rune, s []byte) []byte
Map returns a copy of the byte slice s with all its characters modified
according to the mapping function. If mapping returns a negative value, the
character is dropped from the byte slice with no replacement. The characters
in s and the output are interpreted as UTF-8-encoded code points.
func Repeat(b []byte, count int) []byte
Repeat returns a new byte slice consisting of count copies of b.
It panics if count is negative or if the result of (len(b) * count)
overflows.
func Replace(s, old, new []byte, n int) []byte
Replace returns a copy of the slice s with the first n non-overlapping
instances of old replaced by new. If old is empty, it matches at the
beginning of the slice and after each UTF-8 sequence, yielding up to k+1
replacements for a k-rune slice. If n < 0, there is no limit on the number
of replacements.
func ReplaceAll(s, old, new []byte) []byte
ReplaceAll returns a copy of the slice s with all non-overlapping instances
of old replaced by new. If old is empty, it matches at the beginning of the
slice and after each UTF-8 sequence, yielding up to k+1 replacements for a
k-rune slice.
func Runes(s []byte) []rune
Runes interprets s as a sequence of UTF-8-encoded code points. It returns a
slice of runes (Unicode code points) equivalent to s.
func Split(s, sep []byte) [][]byte
Split slices s into all subslices separated by sep and returns a slice of
the subslices between those separators. If sep is empty, Split splits after
each UTF-8 sequence. It is equivalent to SplitN with a count of -1.
To split around the first instance of a separator, see Cut.
func SplitAfter(s, sep []byte) [][]byte
SplitAfter slices s into all subslices after each instance of sep and
returns a slice of those subslices. If sep is empty, SplitAfter splits after
each UTF-8 sequence. It is equivalent to SplitAfterN with a count of -1.
func SplitAfterN(s, sep []byte, n int) [][]byte
SplitAfterN slices s into subslices after each instance of sep and returns
a slice of those subslices. If sep is empty, SplitAfterN splits after each
UTF-8 sequence. The count determines the number of subslices to return:
- n > 0: at most n subslices; the last subslice will be the unsplit
remainder;
- n == 0: the result is nil (zero subslices);
- n < 0: all subslices.
func SplitAfterSeq(s, sep []byte) iter.Seq[[]byte]
SplitAfterSeq returns an iterator over substrings of s split after each
instance of sep. The iterator yields the same strings that would be returned
by SplitAfter(s, sep), but without constructing the slice. It returns a
single-use iterator.
func SplitN(s, sep []byte, n int) [][]byte
SplitN slices s into subslices separated by sep and returns a slice of the
subslices between those separators. If sep is empty, SplitN splits after
each UTF-8 sequence. The count determines the number of subslices to return:
- n > 0: at most n subslices; the last subslice will be the unsplit
remainder;
- n == 0: the result is nil (zero subslices);
- n < 0: all subslices.
To split around the first instance of a separator, see Cut.
func SplitSeq(s, sep []byte) iter.Seq[[]byte]
SplitSeq returns an iterator over all substrings of s separated by sep.
The iterator yields the same strings that would be returned by Split(s,
sep), but without constructing the slice. It returns a single-use iterator.
func Title(s []byte) []byte
Title treats s as UTF-8-encoded bytes and returns a copy with all Unicode
letters that begin words mapped to their title case.
Deprecated: The rule Title uses for word boundaries does not handle Unicode
punctuation properly. Use golang.org/x/text/cases instead.
func ToLower(s []byte) []byte
ToLower returns a copy of the byte slice s with all Unicode letters mapped
to their lower case.
func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte
ToLowerSpecial treats s as UTF-8-encoded bytes and returns a copy with
all the Unicode letters mapped to their lower case, giving priority to the
special casing rules.
func ToTitle(s []byte) []byte
ToTitle treats s as UTF-8-encoded bytes and returns a copy with all the
Unicode letters mapped to their title case.
func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte
ToTitleSpecial treats s as UTF-8-encoded bytes and returns a copy with
all the Unicode letters mapped to their title case, giving priority to the
special casing rules.
func ToUpper(s []byte) []byte
ToUpper returns a copy of the byte slice s with all Unicode letters mapped
to their upper case.
func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte
ToUpperSpecial treats s as UTF-8-encoded bytes and returns a copy with
all the Unicode letters mapped to their upper case, giving priority to the
special casing rules.
func ToValidUTF8(s, replacement []byte) []byte
ToValidUTF8 treats s as UTF-8-encoded bytes and returns a copy with each run
of bytes representing invalid UTF-8 replaced with the bytes in replacement,
which may be empty.
func Trim(s []byte, cutset string) []byte
Trim returns a subslice of s by slicing off all leading and trailing
UTF-8-encoded code points contained in cutset.
func TrimFunc(s []byte, f func(r rune) bool) []byte
TrimFunc returns a subslice of s by slicing off all leading and trailing
UTF-8-encoded code points c that satisfy f(c).
func TrimLeft(s []byte, cutset string) []byte
TrimLeft returns a subslice of s by slicing off all leading UTF-8-encoded
code points contained in cutset.
func TrimLeftFunc(s []byte, f func(r rune) bool) []byte
TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by
slicing off all leading UTF-8-encoded code points c that satisfy f(c).
func TrimPrefix(s, prefix []byte) []byte
TrimPrefix returns s without the provided leading prefix string. If s
doesn't start with prefix, s is returned unchanged.
func TrimRight(s []byte, cutset string) []byte
TrimRight returns a subslice of s by slicing off all trailing UTF-8-encoded
code points that are contained in cutset.
func TrimRightFunc(s []byte, f func(r rune) bool) []byte
TrimRightFunc returns a subslice of s by slicing off all trailing
UTF-8-encoded code points c that satisfy f(c).
func TrimSpace(s []byte) []byte
TrimSpace returns a subslice of s by slicing off all leading and trailing
white space, as defined by Unicode.
func TrimSuffix(s, suffix []byte) []byte
TrimSuffix returns s without the provided trailing suffix string. If s
doesn't end with suffix, s is returned unchanged.
func containsRune(s string, r rune) bool
containsRune is a simplified version of strings.ContainsRune to avoid
importing the strings package. We avoid bytes.ContainsRune to avoid
allocating a temporary copy of s.
func explode(s []byte, n int) [][]byte
explode splits s into a slice of UTF-8 sequences, one per Unicode code point
(still slices of bytes), up to a maximum of n byte slices. Invalid UTF-8
sequences are chopped into individual bytes.
func explodeSeq(s []byte) iter.Seq[[]byte]
explodeSeq returns an iterator over the runes in s.
func genSplit(s, sep []byte, sepSave, n int) [][]byte
Generic split: splits after each instance of sep, including sepSave bytes of
sep in the subslices.
func growSlice(b []byte, n int) []byte
growSlice grows b by n, preserving the original content of b. If the
allocation fails, it panics with ErrTooLarge.
func indexBytePortable(s []byte, c byte) int
func indexFunc(s []byte, f func(r rune) bool, truth bool) int
indexFunc is the same as IndexFunc except that if truth==false, the sense of
the predicate function is inverted.
func isSeparator(r rune) bool
isSeparator reports whether the rune could mark a word boundary. TODO:
update when package unicode captures more of the properties.
func lastIndexFunc(s []byte, f func(r rune) bool, truth bool) int
lastIndexFunc is the same as LastIndexFunc except that if truth==false,
the sense of the predicate function is inverted.
func splitSeq(s, sep []byte, sepSave int) iter.Seq[[]byte]
splitSeq is SplitSeq or SplitAfterSeq, configured by how many bytes of sep
to include in the results (none or all).
func trimLeftASCII(s []byte, as *asciiSet) []byte
func trimLeftByte(s []byte, c byte) []byte
func trimLeftUnicode(s []byte, cutset string) []byte
func trimRightASCII(s []byte, as *asciiSet) []byte
func trimRightByte(s []byte, c byte) []byte
func trimRightUnicode(s []byte, cutset string) []byte
TYPES
type Buffer struct {
}
A Buffer is a variable-sized buffer of bytes with Buffer.Read and
Buffer.Write methods. The zero value for Buffer is an empty buffer ready to
use.
func NewBuffer(buf []byte) *Buffer
NewBuffer creates and initializes a new Buffer using buf as its initial
contents. The new Buffer takes ownership of buf, and the caller should not
use buf after this call. NewBuffer is intended to prepare a Buffer to read
existing data. It can also be used to set the initial size of the internal
buffer for writing. To do that, buf should have the desired capacity but a
length of zero.
In most cases, new(Buffer) (or just declaring a Buffer variable) is
sufficient to initialize a Buffer.
func NewBufferString(s string) *Buffer
NewBufferString creates and initializes a new Buffer using string s as its
initial contents. It is intended to prepare a buffer to read an existing
string.
In most cases, new(Buffer) (or just declaring a Buffer variable) is
sufficient to initialize a Buffer.
func (b *Buffer) Available() int
Available returns how many bytes are unused in the buffer.
func (b *Buffer) AvailableBuffer() []byte
AvailableBuffer returns an empty buffer with b.Available() capacity. This
buffer is intended to be appended to and passed to an immediately succeeding
Buffer.Write call. The buffer is only valid until the next write operation
on b.
func (b *Buffer) Bytes() []byte
Bytes returns a slice of length b.Len() holding the unread portion of the
buffer. The slice is valid for use only until the next buffer modification
(that is, only until the next call to a method like Buffer.Read,
Buffer.Write, Buffer.Reset, or Buffer.Truncate). The slice aliases the
buffer content at least until the next buffer modification, so immediate
changes to the slice will affect the result of future reads.
func (b *Buffer) Cap() int
Cap returns the capacity of the buffer's underlying byte slice, that is,
the total space allocated for the buffer's data.
func (b *Buffer) Grow(n int)
Grow grows the buffer's capacity, if necessary, to guarantee space for
another n bytes. After Grow(n), at least n bytes can be written to the
buffer without another allocation. If n is negative, Grow will panic.
If the buffer can't grow it will panic with ErrTooLarge.
func (b *Buffer) Len() int
Len returns the number of bytes of the unread portion of the buffer; b.Len()
== len(b.Bytes()).
func (b *Buffer) Next(n int) []byte
Next returns a slice containing the next n bytes from the buffer,
advancing the buffer as if the bytes had been returned by Buffer.Read. If
there are fewer than n bytes in the buffer, Next returns the entire buffer.
The slice is only valid until the next call to a read or write method.
func (b *Buffer) Read(p []byte) (n int, err error)
Read reads the next len(p) bytes from the buffer or until the buffer is
drained. The return value n is the number of bytes read. If the buffer has
no data to return, err is io.EOF (unless len(p) is zero); otherwise it is
nil.
func (b *Buffer) ReadByte() (byte, error)
ReadByte reads and returns the next byte from the buffer. If no byte is
available, it returns error io.EOF.
func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)
ReadBytes reads until the first occurrence of delim in the input,
returning a slice containing the data up to and including the delimiter.
If ReadBytes encounters an error before finding a delimiter, it returns the
data read before the error and the error itself (often io.EOF). ReadBytes
returns err != nil if and only if the returned data does not end in delim.
func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
ReadFrom reads data from r until EOF and appends it to the buffer, growing
the buffer as needed. The return value n is the number of bytes read.
Any error except io.EOF encountered during the read is also returned.
If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.
func (b *Buffer) ReadRune() (r rune, size int, err error)
ReadRune reads and returns the next UTF-8-encoded Unicode code point from
the buffer. If no bytes are available, the error returned is io.EOF. If the
bytes are an erroneous UTF-8 encoding, it consumes one byte and returns
U+FFFD, 1.
func (b *Buffer) ReadString(delim byte) (line string, err error)
ReadString reads until the first occurrence of delim in the input,
returning a string containing the data up to and including the delimiter.
If ReadString encounters an error before finding a delimiter, it returns the
data read before the error and the error itself (often io.EOF). ReadString
returns err != nil if and only if the returned data does not end in delim.
func (b *Buffer) Reset()
Reset resets the buffer to be empty, but it retains the underlying storage
for use by future writes. Reset is the same as Buffer.Truncate(0).
func (b *Buffer) String() string
String returns the contents of the unread portion of the buffer as a string.
If the Buffer is a nil pointer, it returns "<nil>".
To build strings more efficiently, see the strings.Builder type.
func (b *Buffer) Truncate(n int)
Truncate discards all but the first n unread bytes from the buffer but
continues to use the same allocated storage. It panics if n is negative or
greater than the length of the buffer.
func (b *Buffer) UnreadByte() error
UnreadByte unreads the last byte returned by the most recent successful
read operation that read at least one byte. If a write has happened since
the last read, if the last read returned an error, or if the read read zero
bytes, UnreadByte returns an error.
func (b *Buffer) UnreadRune() error
UnreadRune unreads the last rune returned by Buffer.ReadRune. If the
most recent read or write operation on the buffer was not a successful
Buffer.ReadRune, UnreadRune returns an error. (In this regard it is stricter
than Buffer.UnreadByte, which will unread the last byte from any read
operation.)
func (b *Buffer) Write(p []byte) (n int, err error)
Write appends the contents of p to the buffer, growing the buffer as needed.
The return value n is the length of p; err is always nil. If the buffer
becomes too large, Write will panic with ErrTooLarge.
func (b *Buffer) WriteByte(c byte) error
WriteByte appends the byte c to the buffer, growing the buffer as needed.
The returned error is always nil, but is included to match bufio.Writer's
WriteByte. If the buffer becomes too large, WriteByte will panic with
ErrTooLarge.
func (b *Buffer) WriteRune(r rune) (n int, err error)
WriteRune appends the UTF-8 encoding of Unicode code point r to the buffer,
returning its length and an error, which is always nil but is included to
match bufio.Writer's WriteRune. The buffer is grown as needed; if it becomes
too large, WriteRune will panic with ErrTooLarge.
func (b *Buffer) WriteString(s string) (n int, err error)
WriteString appends the contents of s to the buffer, growing the buffer as
needed. The return value n is the length of s; err is always nil. If the
buffer becomes too large, WriteString will panic with ErrTooLarge.
func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)
WriteTo writes data to w until the buffer is drained or an error occurs. The
return value n is the number of bytes written; it always fits into an int,
but it is int64 to match the io.WriterTo interface. Any error encountered
during the write is also returned.
func (b *Buffer) empty() bool
empty reports whether the unread portion of the buffer is empty.
func (b *Buffer) grow(n int) int
grow grows the buffer to guarantee space for n more bytes. It returns the
index where bytes should be written. If the buffer can't grow it will panic
with ErrTooLarge.
func (b *Buffer) readSlice(delim byte) (line []byte, err error)
readSlice is like ReadBytes but returns a reference to internal buffer data.
func (b *Buffer) tryGrowByReslice(n int) (int, bool)
tryGrowByReslice is an inlineable version of grow for the fast-case where
the internal buffer only needs to be resliced. It returns the index where
bytes should be written and whether it succeeded.
type Reader struct {
s []byte
}
A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker,
io.ByteScanner, and io.RuneScanner interfaces by reading from a byte slice.
Unlike a Buffer, a Reader is read-only and supports seeking. The zero value
for Reader operates like a Reader of an empty slice.
func NewReader(b []byte) *Reader
NewReader returns a new Reader reading from b.
func (r *Reader) Len() int
Len returns the number of bytes of the unread portion of the slice.
func (r *Reader) Read(b []byte) (n int, err error)
Read implements the io.Reader interface.
func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)
ReadAt implements the io.ReaderAt interface.
func (r *Reader) ReadByte() (byte, error)
ReadByte implements the io.ByteReader interface.
func (r *Reader) ReadRune() (ch rune, size int, err error)
ReadRune implements the io.RuneReader interface.
func (r *Reader) Reset(b []byte)
Reset resets the Reader to be reading from b.
func (r *Reader) Seek(offset int64, whence int) (int64, error)
Seek implements the io.Seeker interface.
func (r *Reader) Size() int64
Size returns the original length of the underlying byte slice. Size is
the number of bytes available for reading via Reader.ReadAt. The result is
unaffected by any method calls except Reader.Reset.
func (r *Reader) UnreadByte() error
UnreadByte complements Reader.ReadByte in implementing the io.ByteScanner
interface.
func (r *Reader) UnreadRune() error
UnreadRune complements Reader.ReadRune in implementing the io.RuneScanner
interface.
func (r *Reader) WriteTo(w io.Writer) (n int64, err error)
WriteTo implements the io.WriterTo interface.
type asciiSet [8]uint32
asciiSet is a 32-byte value, where each bit represents the presence of
a given ASCII character in the set. The 128-bits of the lower 16 bytes,
starting with the least-significant bit of the lowest word to the
most-significant bit of the highest word, map to the full range of all
128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed,
ensuring that any non-ASCII character will be reported as not in the set.
This allocates a total of 32 bytes even though the upper half is unused to
avoid bounds checks in asciiSet.contains.
func makeASCIISet(chars string) (as asciiSet, ok bool)
makeASCIISet creates a set of ASCII characters and reports whether all
characters in chars are ASCII.
func (as *asciiSet) contains(c byte) bool
contains reports whether c is inside the set.
type readOp int8
The readOp constants describe the last action performed on the buffer,
so that UnreadRune and UnreadByte can check for invalid usage. opReadRuneX
constants are chosen such that converted to int they correspond to the rune
size that was read.
const (
)
Don't use iota for these, as the values need to correspond with the names
and comments, which is easier to see when being explicit.
cmp
func Compare[T Ordered](x, y T) int
Compare returns
-1 if x is less than y,
0 if x equals y,
+1 if x is greater than y.
For floating-point types, a NaN is considered less than any non-NaN,
a NaN is considered equal to a NaN, and -0.0 is equal to 0.0.
func Less[T Ordered](x, y T) bool
Less reports whether x is less than y. For floating-point types, a NaN is
considered less than any non-NaN, and -0.0 is not less than (is equal to)
0.0.
func Or[T comparable](vals ...T) T
Or returns the first of its arguments that is not equal to the zero value.
If no argument is non-zero, it returns the zero value.
func isNaN[T Ordered](x T) bool
isNaN reports whether x is a NaN without requiring the math package.
This will always return false if T is not floating-point.
TYPES
type Ordered interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64 |
~string
}
Ordered is a constraint that permits any ordered type: any type that
supports the operators < <= >= >. If future releases of Go add new ordered
types, this constraint will be modified to include them.
Note that floating-point types may contain NaN ("not-a-number") values. An
operator such as == or < will always report false when comparing a NaN value
with any other value, NaN or not. See the Compare function for a consistent
way to compare NaN values.
compress/bzip2
func NewReader(r io.Reader) io.Reader
NewReader returns an io.Reader which decompresses bzip2 data from r.
If r does not also implement io.ByteReader, the decompressor may read more
data than necessary from r.
func buildHuffmanNode(t *huffmanTree, codes []huffmanCode, level uint32) (nodeIndex uint16, err error)
buildHuffmanNode takes a slice of sorted huffmanCodes and builds a node
in the Huffman tree at the given level. It returns the index of the newly
constructed node.
func init()
func inverseBWT(tt []uint32, origPtr uint, c []uint) uint32
inverseBWT implements the inverse Burrows-Wheeler transform as described in
In that document, origPtr is called “I” and c is the “C” array after the
first pass over the data. It's an argument here because we merge the first
pass with the Huffman decoding.
This also implements the “single array” method from the bzip2 source code
which leaves the output, still shuffled, in the bottom 8 bits of tt with the
index of the next byte in the top 24-bits. The index of the first byte is
returned.
func updateCRC(val uint32, b []byte) uint32
updateCRC updates the crc value to incorporate the data in b. The initial
value is 0.
TYPES
type StructuralError string
A StructuralError is returned when the bzip2 data is found to be
syntactically invalid.
func (s StructuralError) Error() string
type bitReader struct {
r io.ByteReader
n uint64
bits uint
err error
}
bitReader wraps an io.Reader and provides the ability to read values,
bit-by-bit, from it. Its Read* methods don't return the usual error because
the error handling was verbose. Instead, any error is kept and can be
checked afterwards.
func newBitReader(r io.Reader) bitReader
newBitReader returns a new bitReader reading from r. If r is not already an
io.ByteReader, it will be converted via a bufio.Reader.
func (br *bitReader) Err() error
func (br *bitReader) ReadBit() bool
func (br *bitReader) ReadBits(bits uint) (n int)
func (br *bitReader) ReadBits64(bits uint) (n uint64)
ReadBits64 reads the given number of bits and returns them in the
least-significant part of a uint64. In the event of an error, it returns 0
and the error can be obtained by calling bitReader.Err().
type huffmanCode struct {
code uint32
codeLen uint8
value uint16
}
huffmanCode contains a symbol, its code and code length.
type huffmanNode struct {
left, right uint16
leftValue, rightValue uint16
}
A huffmanNode is a node in the tree. left and right contain indexes into the
nodes slice of the tree. If left or right is invalidNodeValue then the child
is a left node and its value is in leftValue/rightValue.
The symbols are uint16s because bzip2 encodes not only MTF indexes in the
tree, but also two magic values for run-length encoding and an EOF symbol.
Thus there are more than 256 possible symbols.
type huffmanSymbolLengthPair struct {
value uint16
length uint8
}
huffmanSymbolLengthPair contains a symbol and its code length.
type huffmanTree struct {
nodes []huffmanNode
nextNode int
}
A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a
symbol.
func newHuffmanTree(lengths []uint8) (huffmanTree, error)
newHuffmanTree builds a Huffman tree from a slice containing the code
lengths of each symbol. The maximum code length is 32 bits.
func (t *huffmanTree) Decode(br *bitReader) (v uint16)
Decode reads bits from the given bitReader and navigates the tree until a
symbol is found.
type moveToFrontDecoder []byte
moveToFrontDecoder implements a move-to-front list. Such a list is an
efficient way to transform a string with repeating elements into one with
many small valued numbers, which is suitable for entropy encoding. It works
by starting with an initial list of symbols and references symbols by their
index into that list. When a symbol is referenced, it's moved to the front
of the list. Thus, a repeated symbol ends up being encoded with many zeros,
as the symbol will be at the front of the list after the first access.
func newMTFDecoder(symbols []byte) moveToFrontDecoder
newMTFDecoder creates a move-to-front decoder with an explicit initial list
of symbols.
func newMTFDecoderWithRange(n int) moveToFrontDecoder
newMTFDecoderWithRange creates a move-to-front decoder with an initial
symbol list of 0...n-1.
func (m moveToFrontDecoder) Decode(n int) (b byte)
func (m moveToFrontDecoder) First() byte
First returns the symbol at the front of the list.
type reader struct {
br bitReader
fileCRC uint32
blockCRC uint32
wantBlockCRC uint32
eof bool
}
A reader decompresses bzip2 compressed data.
func (bz2 *reader) Read(buf []byte) (n int, err error)
func (bz2 *reader) read(buf []byte) (int, error)
func (bz2 *reader) readBlock() (err error)
readBlock reads a bzip2 block. The magic number should already have been
consumed.
func (bz2 *reader) readFromBlock(buf []byte) int
func (bz2 *reader) setup(needMagic bool) error
setup parses the bzip2 header.
compress/flate
func NewReader(r io.Reader) io.ReadCloser
NewReader returns a new ReadCloser that can be used to read the uncompressed
version of r. If r does not also implement io.ByteReader, the decompressor
may read more data than necessary from r. The reader returns io.EOF after
the final block in the DEFLATE stream has been encountered. Any trailing
data after the final block is ignored.
The io.ReadCloser returned by NewReader also implements Resetter.
func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser
NewReaderDict is like NewReader but initializes the reader with a preset
dictionary. The returned Reader behaves as if the uncompressed data
stream started with the given dictionary, which has already been read.
NewReaderDict is typically used to read data compressed by NewWriterDict.
The ReadCloser returned by NewReaderDict also implements Resetter.
func bulkHash4(b []byte, dst []uint32)
bulkHash4 will compute hashes using the same algorithm as hash4.
func fixedHuffmanDecoderInit()
func hash(u uint32) uint32
func hash4(b []byte) uint32
hash4 returns a hash representation of the first 4 bytes of the supplied
slice. The caller must ensure that len(b) >= 4.
func histogram(b []byte, h []int32)
histogram accumulates a histogram of b in h.
len(h) must be >= 256, and h's elements must be all zeroes.
func init()
func lengthCode(len uint32) uint32
func load32(b []byte, i int32) uint32
func load64(b []byte, i int32) uint64
func matchLen(a, b []byte, max int) int
matchLen returns the number of matching bytes in a and b up to length 'max'.
Both slices must be at least 'max' bytes in size.
func noEOF(e error) error
noEOF returns err, unless err == io.EOF, in which case it returns
io.ErrUnexpectedEOF.
func offsetCode(off uint32) uint32
Returns the offset code corresponding to a specific offset.
func reverseBits(number uint16, bitLength byte) uint16
TYPES
type CorruptInputError int64
A CorruptInputError reports the presence of corrupt input at a given offset.
func (e CorruptInputError) Error() string
type InternalError string
An InternalError reports an error in the flate code itself.
func (e InternalError) Error() string
type ReadError struct {
}
A ReadError reports an error encountered while reading input.
Deprecated: No longer returned.
func (e *ReadError) Error() string
type Reader interface {
io.Reader
io.ByteReader
}
The actual read interface needed by NewReader. If the passed in io.Reader
does not also have ReadByte, the NewReader will introduce its own buffering.
type Resetter interface {
Reset(r io.Reader, dict []byte) error
}
Resetter resets a ReadCloser returned by NewReader or NewReaderDict to
switch to a new underlying Reader. This permits reusing a ReadCloser instead
of allocating a new one.
type WriteError struct {
}
A WriteError reports an error encountered while writing output.
Deprecated: No longer returned.
func (e *WriteError) Error() string
type Writer struct {
d compressor
dict []byte
}
A Writer takes data written to it and writes the compressed form of that
data to an underlying writer (see NewWriter).
func NewWriter(w io.Writer, level int) (*Writer, error)
NewWriter returns a new Writer compressing data at the given level.
Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression);
higher levels typically run slower but compress more. Level 0
(NoCompression) does not attempt any compression; it only adds the necessary
DEFLATE framing. Level -1 (DefaultCompression) uses the default compression
level. Level -2 (HuffmanOnly) will use Huffman compression only, giving a
very fast compression for all types of input, but sacrificing considerable
compression efficiency.
If level is in the range [-2, 9] then the error returned will be nil.
Otherwise the error returned will be non-nil.
func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error)
NewWriterDict is like NewWriter but initializes the new Writer with a
preset dictionary. The returned Writer behaves as if the dictionary had been
written to it without producing any compressed output. The compressed data
written to w can only be decompressed by a Reader initialized with the same
dictionary.
func (w *Writer) Close() error
Close flushes and closes the writer.
func (w *Writer) Flush() error
Flush flushes any pending data to the underlying writer. It is useful mainly
in compressed network protocols, to ensure that a remote reader has enough
data to reconstruct a packet. Flush does not return until the data has been
written. Calling Flush when there is no pending data still causes the Writer
to emit a sync marker of at least 4 bytes. If the underlying writer returns
an error, Flush returns that error.
In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
func (w *Writer) Reset(dst io.Writer)
Reset discards the writer's state and makes it equivalent to the result of
NewWriter or NewWriterDict called with dst and w's level and dictionary.
func (w *Writer) Write(data []byte) (n int, err error)
Write writes data to w, which will eventually write the compressed form of
data to its underlying writer.
type byFreq []literalNode
func (s byFreq) Len() int
func (s byFreq) Less(i, j int) bool
func (s byFreq) Swap(i, j int)
func (s *byFreq) sort(a []literalNode)
type byLiteral []literalNode
func (s byLiteral) Len() int
func (s byLiteral) Less(i, j int) bool
func (s byLiteral) Swap(i, j int)
func (s *byLiteral) sort(a []literalNode)
type compressionLevel struct {
level, good, lazy, nice, chain, fastSkipHashing int
}
type compressor struct {
compressionLevel
w *huffmanBitWriter
bulkHasher func([]byte, []uint32)
chainHead int
hashHead [hashSize]uint32
hashPrev [windowSize]uint32
hashOffset int
index int
window []byte
windowEnd int
tokens []token
length int
offset int
maxInsertIndex int
err error
hashMatch [maxMatchLength - 1]uint32
}
func (d *compressor) close() error
func (d *compressor) deflate()
func (d *compressor) encSpeed()
encSpeed will compress and store the currently added data, if enough has
been accumulated or we at the end of the stream. Any error that occurred
will be in d.err
func (d *compressor) fillDeflate(b []byte) int
func (d *compressor) fillStore(b []byte) int
func (d *compressor) fillWindow(b []byte)
fillWindow will fill the current window with the supplied dictionary and
calculate all hashes. This is much faster than doing a full encode. Should
only be used after a reset.
func (d *compressor) findMatch(pos int, prevHead int, prevLength int, lookahead int) (length, offset int, ok bool)
Try to find a match starting at index whose length is greater than prevSize.
We only look at chainCount possibilities before giving up.
func (d *compressor) init(w io.Writer, level int) (err error)
func (d *compressor) initDeflate()
func (d *compressor) reset(w io.Writer)
func (d *compressor) store()
func (d *compressor) storeHuff()
storeHuff compresses and stores the currently added data when the d.window
is full or we are at the end of the stream. Any error that occurred will be
in d.err
func (d *compressor) syncFlush() error
func (d *compressor) write(b []byte) (n int, err error)
func (d *compressor) writeBlock(tokens []token, index int) error
func (d *compressor) writeStoredBlock(buf []byte) error
type decompressor struct {
r Reader
roffset int64
b uint32
nb uint
h1, h2 huffmanDecoder
bits *[maxNumLit + maxNumDist]int
codebits *[numCodes]int
dict dictDecoder
buf [4]byte
step func(*decompressor)
stepState int
final bool
err error
toRead []byte
hl, hd *huffmanDecoder
copyLen int
copyDist int
}
Decompress state.
func (f *decompressor) Close() error
func (f *decompressor) Read(b []byte) (int, error)
func (f *decompressor) Reset(r io.Reader, dict []byte) error
func (f *decompressor) copyData()
copyData copies f.copyLen bytes from the underlying reader into f.hist.
It pauses for reads when f.hist is full.
func (f *decompressor) dataBlock()
Copy a single uncompressed data block from input to output.
func (f *decompressor) finishBlock()
func (f *decompressor) huffSym(h *huffmanDecoder) (int, error)
Read the next Huffman-encoded symbol from f according to h.
func (f *decompressor) huffmanBlock()
Decode a single Huffman block from f. hl and hd are the Huffman states for
the lit/length values and the distance values, respectively. If hd == nil,
using the fixed distance encoding associated with fixed Huffman blocks.
func (f *decompressor) makeReader(r io.Reader)
func (f *decompressor) moreBits() error
func (f *decompressor) nextBlock()
func (f *decompressor) readHuffman() error
type deflateFast struct {
table [tableSize]tableEntry
}
deflateFast maintains the table for matches, and the previous byte block for
cross block matching.
func newDeflateFast() *deflateFast
func (e *deflateFast) encode(dst []token, src []byte) []token
encode encodes a block given in src and appends tokens to dst and returns
the result.
func (e *deflateFast) matchLen(s, t int32, src []byte) int32
matchLen returns the match length between src[s:] and src[t:]. t can be
negative to indicate the match is starting in e.prev. We assume that
src[s-4:s] and src[t-4:t] already match.
func (e *deflateFast) reset()
Reset resets the encoding history. This ensures that no matches are made to
the previous block.
func (e *deflateFast) shiftOffsets()
shiftOffsets will shift down all match offset. This is only called in rare
situations to prevent integer overflow.
type dictDecoder struct {
}
dictDecoder implements the LZ77 sliding dictionary as used in decompression.
LZ77 decompresses data through sequences of two forms of commands:
- Literal insertions: Runs of one or more symbols are inserted into the
data stream as is. This is accomplished through the writeByte method for
a single symbol, or combinations of writeSlice/writeMark for multiple
symbols. Any valid stream must start with a literal insertion if no
preset dictionary is used.
- Backward copies: Runs of one or more symbols are copied from previously
emitted data. Backward copies come as the tuple (dist, length) where
dist determines how far back in the stream to copy from and length
determines how many bytes to copy. Note that it is valid for the length
to be greater than the distance. Since LZ77 uses forward copies, that
situation is used to perform a form of run-length encoding on repeated
runs of symbols. The writeCopy and tryWriteCopy are used to implement
this command.
For performance reasons, this implementation performs little to no sanity
checks about the arguments. As such, the invariants documented for each
method call must be respected.
func (dd *dictDecoder) availRead() int
availRead reports the number of bytes that can be flushed by readFlush.
func (dd *dictDecoder) availWrite() int
availWrite reports the available amount of output buffer space.
func (dd *dictDecoder) histSize() int
histSize reports the total amount of historical data in the dictionary.
func (dd *dictDecoder) init(size int, dict []byte)
init initializes dictDecoder to have a sliding window dictionary of the
given size. If a preset dict is provided, it will initialize the dictionary
with the contents of dict.
func (dd *dictDecoder) readFlush() []byte
readFlush returns a slice of the historical buffer that is ready to be
emitted to the user. The data returned by readFlush must be fully consumed
before calling any other dictDecoder methods.
func (dd *dictDecoder) tryWriteCopy(dist, length int) int
tryWriteCopy tries to copy a string at a given (distance, length) to the
output. This specialized version is optimized for short distances.
This method is designed to be inlined for performance reasons.
This invariant must be kept: 0 < dist <= histSize()
func (dd *dictDecoder) writeByte(c byte)
writeByte writes a single byte to the dictionary.
This invariant must be kept: 0 < availWrite()
func (dd *dictDecoder) writeCopy(dist, length int) int
writeCopy copies a string at a given (dist, length) to the output. This
returns the number of bytes copied and may be less than the requested length
if the available space in the output buffer is too small.
This invariant must be kept: 0 < dist <= histSize()
func (dd *dictDecoder) writeMark(cnt int)
writeMark advances the writer pointer by cnt.
This invariant must be kept: 0 <= cnt <= availWrite()
func (dd *dictDecoder) writeSlice() []byte
writeSlice returns a slice of the available buffer to write data to.
This invariant will be kept: len(s) <= availWrite()
type dictWriter struct {
w io.Writer
}
func (w *dictWriter) Write(b []byte) (n int, err error)
type hcode struct {
code, len uint16
}
hcode is a huffman code with a bit code and bit length.
func (h *hcode) set(code uint16, length uint16)
set sets the code and length of an hcode.
type huffmanBitWriter struct {
writer io.Writer
bits uint64
nbits uint
bytes [bufferSize]byte
codegenFreq [codegenCodeCount]int32
nbytes int
literalFreq []int32
offsetFreq []int32
codegen []uint8
literalEncoding *huffmanEncoder
offsetEncoding *huffmanEncoder
codegenEncoding *huffmanEncoder
err error
}
func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter
func (w *huffmanBitWriter) dynamicSize(litEnc, offEnc *huffmanEncoder, extraBits int) (size, numCodegens int)
dynamicSize returns the size of dynamically encoded data in bits.
func (w *huffmanBitWriter) fixedSize(extraBits int) int
fixedSize returns the size of dynamically encoded data in bits.
func (w *huffmanBitWriter) flush()
func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litEnc, offEnc *huffmanEncoder)
RFC 1951 3.2.7 specifies a special run-length encoding for specifying the
literal and offset lengths arrays (which are concatenated into a single
array). This method generates that run-length encoding.
The result is written into the codegen array, and the frequencies of each
code is written into the codegenFreq array. Codes 0-15 are single byte
codes. Codes 16-18 are followed by additional information. Code badCode is
an end marker
numLiterals The number of literals in literalEncoding
numOffsets The number of offsets in offsetEncoding
litenc, offenc The literal and offset encoder to use
func (w *huffmanBitWriter) indexTokens(tokens []token) (numLiterals, numOffsets int)
indexTokens indexes a slice of tokens, and updates literalFreq and
offsetFreq, and generates literalEncoding and offsetEncoding. The number of
literal and offset tokens is returned.
func (w *huffmanBitWriter) reset(writer io.Writer)
func (w *huffmanBitWriter) storedSize(in []byte) (int, bool)
storedSize calculates the stored size, including header. The function
returns the size in bits and whether the block fits inside a single block.
func (w *huffmanBitWriter) write(b []byte)
func (w *huffmanBitWriter) writeBits(b int32, nb uint)
func (w *huffmanBitWriter) writeBlock(tokens []token, eof bool, input []byte)
writeBlock will write a block of tokens with the smallest encoding.
The original input can be supplied, and if the huffman encoded data is
larger than the original bytes, the data will be written as a stored block.
If the input is nil, the tokens will always be Huffman encoded.
func (w *huffmanBitWriter) writeBlockDynamic(tokens []token, eof bool, input []byte)
writeBlockDynamic encodes a block using a dynamic Huffman table. This should
be used if the symbols used have a disproportionate histogram distribution.
If input is supplied and the compression savings are below 1/16th of the
input size the block is stored.
func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte)
writeBlockHuff encodes a block of bytes as either Huffman encoded
literals or uncompressed bytes if the results only gains very little from
compression.
func (w *huffmanBitWriter) writeBytes(bytes []byte)
func (w *huffmanBitWriter) writeCode(c hcode)
func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, numCodegens int, isEof bool)
Write the header of a dynamic Huffman block to the output stream.
numLiterals The number of literals specified in codegen
numOffsets The number of offsets specified in codegen
numCodegens The number of codegens used in codegen
func (w *huffmanBitWriter) writeFixedHeader(isEof bool)
func (w *huffmanBitWriter) writeStoredHeader(length int, isEof bool)
func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode)
writeTokens writes a slice of tokens to the output. codes for literal and
offset encoding must be supplied.
type huffmanDecoder struct {
}
var fixedHuffmanDecoder huffmanDecoder
func (h *huffmanDecoder) init(lengths []int) bool
Initialize Huffman decoding tables from array of code lengths. Following
this function, h is guaranteed to be initialized into a complete tree (i.e.,
neither over-subscribed nor under-subscribed). The exception is a degenerate
case where the tree has only a single symbol with length 1. Empty trees are
permitted.
type huffmanEncoder struct {
codes []hcode
freqcache []literalNode
bitCount [17]int32
}
var fixedLiteralEncoding *huffmanEncoder = generateFixedLiteralEncoding()
var fixedOffsetEncoding *huffmanEncoder = generateFixedOffsetEncoding()
var huffOffset *huffmanEncoder
huffOffset is a static offset encoder used for huffman only encoding.
It can be reused since we will not be encoding offset values.
func generateFixedLiteralEncoding() *huffmanEncoder
Generates a HuffmanCode corresponding to the fixed literal table.
func generateFixedOffsetEncoding() *huffmanEncoder
func newHuffmanEncoder(size int) *huffmanEncoder
func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode)
Look at the leaves and assign them a bit count and an encoding as specified
in RFC 1951 3.2.2
func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32
bitCounts computes the number of literals assigned to each bit size in the
Huffman encoding. It is only called when list.length >= 3. The cases of 0,
1, and 2 literals are handled by special case code.
list is an array of the literals with non-zero frequencies and their
associated frequencies. The array is in order of increasing frequency and
has as its last element a special element with frequency MaxInt32.
maxBits is the maximum number of bits that should be used to encode any
literal. It must be less than 16.
bitCounts returns an integer slice in which slice[i] indicates the number of
literals that should be encoded in i bits.
func (h *huffmanEncoder) bitLength(freq []int32) int
func (h *huffmanEncoder) generate(freq []int32, maxBits int32)
Update this Huffman Code object to be the minimum code for the specified
frequency count.
freq is an array of frequencies, in which freq[i] gives the frequency of
literal i. maxBits The maximum number of bits to use for any literal.
type levelInfo struct {
level int32
lastFreq int32
nextCharFreq int32
nextPairFreq int32
needed int32
}
A levelInfo describes the state of the constructed tree for a given depth.
type literalNode struct {
literal uint16
freq int32
}
func maxNode() literalNode
type tableEntry struct {
offset int32
}
type token uint32
func emitLiteral(dst []token, lit []byte) []token
func literalToken(literal uint32) token
Convert a literal into a literal token.
func matchToken(xlength uint32, xoffset uint32) token
Convert a < xlength, xoffset > pair into a match token.
func (t token) length() uint32
func (t token) literal() uint32
Returns the literal of a literal token.
func (t token) offset() uint32
Returns the extra offset of a match token.
compress/gzip
func noEOF(err error) error
noEOF converts io.EOF to io.ErrUnexpectedEOF.
TYPES
type Header struct {
}
The gzip file stores a header giving metadata about the compressed file.
That header is exposed as the fields of the Writer and Reader structs.
Strings must be UTF-8 encoded and may only contain Unicode code points
U+0001 through U+00FF, due to limitations of the GZIP file format.
type Reader struct {
r flate.Reader
decompressor io.ReadCloser
buf [512]byte
err error
multistream bool
}
A Reader is an io.Reader that can be read to retrieve uncompressed data from
a gzip-format compressed file.
In general, a gzip file can be a concatenation of gzip files, each with
its own header. Reads from the Reader return the concatenation of the
uncompressed data of each. Only the first header is recorded in the Reader
fields.
Gzip files store a length and checksum of the uncompressed data.
The Reader will return an ErrChecksum when Reader.Read reaches the end of
the uncompressed data if it does not have the expected length or checksum.
Clients should treat data returned by Reader.Read as tentative until they
receive the io.EOF marking the end of the data.
func NewReader(r io.Reader) (*Reader, error)
NewReader creates a new Reader reading the given reader. If r does not also
implement io.ByteReader, the decompressor may read more data than necessary
from r.
It is the caller's responsibility to call Close on the Reader when done.
The [Reader.Header] fields will be valid in the Reader returned.
func (z *Reader) Close() error
Close closes the Reader. It does not close the underlying io.Reader.
In order for the GZIP checksum to be verified, the reader must be fully
consumed until the io.EOF.
func (z *Reader) Multistream(ok bool)
Multistream controls whether the reader supports multistream files.
If enabled (the default), the Reader expects the input to be a sequence of
individually gzipped data streams, each with its own header and trailer,
ending at EOF. The effect is that the concatenation of a sequence of gzipped
files is treated as equivalent to the gzip of the concatenation of the
sequence. This is standard behavior for gzip readers.
Calling Multistream(false) disables this behavior; disabling the behavior
can be useful when reading file formats that distinguish individual gzip
data streams or mix gzip data streams with other data streams. In this mode,
when the Reader reaches the end of the data stream, Reader.Read returns
io.EOF. The underlying reader must implement io.ByteReader in order to be
left positioned just after the gzip stream. To start the next stream, call
z.Reset(r) followed by z.Multistream(false). If there is no next stream,
z.Reset(r) will return io.EOF.
func (z *Reader) Read(p []byte) (n int, err error)
Read implements io.Reader, reading uncompressed bytes from its underlying
Reader.
func (z *Reader) Reset(r io.Reader) error
Reset discards the Reader z's state and makes it equivalent to the result of
its original state from NewReader, but reading from r instead. This permits
reusing a Reader rather than allocating a new one.
func (z *Reader) readHeader() (hdr Header, err error)
readHeader reads the GZIP header according to section 2.3.1. This method
does not set z.err.
func (z *Reader) readString() (string, error)
readString reads a NUL-terminated string from z.r. It treats the bytes read
as being encoded as ISO 8859-1 (Latin-1) and will output a string encoded
using UTF-8. This method always updates z.digest with the data read.
type Writer struct {
w io.Writer
level int
wroteHeader bool
closed bool
buf [10]byte
compressor *flate.Writer
err error
}
A Writer is an io.WriteCloser. Writes to a Writer are compressed and written
to w.
func NewWriter(w io.Writer) *Writer
NewWriter returns a new Writer. Writes to the returned writer are compressed
and written to w.
It is the caller's responsibility to call Close on the Writer when done.
Writes may be buffered and not flushed until Close.
Callers that wish to set the fields in Writer.Header must do so before the
first call to Write, Flush, or Close.
func NewWriterLevel(w io.Writer, level int) (*Writer, error)
NewWriterLevel is like NewWriter but specifies the compression level instead
of assuming DefaultCompression.
The compression level can be DefaultCompression, NoCompression, HuffmanOnly
or any integer value between BestSpeed and BestCompression inclusive.
The error returned will be nil if the level is valid.
func (z *Writer) Close() error
Close closes the Writer by flushing any unwritten data to the underlying
io.Writer and writing the GZIP footer. It does not close the underlying
io.Writer.
func (z *Writer) Flush() error
Flush flushes any pending compressed data to the underlying writer.
It is useful mainly in compressed network protocols, to ensure that a remote
reader has enough data to reconstruct a packet. Flush does not return until
the data has been written. If the underlying writer returns an error,
Flush returns that error.
In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH.
func (z *Writer) Reset(w io.Writer)
Reset discards the Writer z's state and makes it equivalent to the result
of its original state from NewWriter or NewWriterLevel, but writing to w
instead. This permits reusing a Writer rather than allocating a new one.
func (z *Writer) Write(p []byte) (int, error)
Write writes a compressed form of p to the underlying io.Writer. The
compressed bytes are not necessarily flushed until the Writer is closed.
func (z *Writer) init(w io.Writer, level int)
func (z *Writer) writeBytes(b []byte) error
writeBytes writes a length-prefixed byte slice to z.w.
func (z *Writer) writeString(s string) (err error)
writeString writes a UTF-8 string s in GZIP's format to z.w. GZIP (RFC 1952)
specifies that strings are NUL-terminated ISO 8859-1 (Latin-1).
compress/lzw
func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser
NewReader creates a new io.ReadCloser. Reads from the returned io.ReadCloser
read and decompress data from r. If r does not also implement io.ByteReader,
the decompressor may read more data than necessary from r. It is the
caller's responsibility to call Close on the ReadCloser when finished
reading. The number of bits to use for literal codes, litWidth, must be in
the range [2,8] and is typically 8. It must equal the litWidth used during
compression.
It is guaranteed that the underlying type of the returned io.ReadCloser is a
*Reader.
func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser
NewWriter creates a new io.WriteCloser. Writes to the returned
io.WriteCloser are compressed and written to w. It is the caller's
responsibility to call Close on the WriteCloser when finished writing.
The number of bits to use for literal codes, litWidth, must be in the range
[2,8] and is typically 8. Input bytes must be less than 1<<litWidth.
It is guaranteed that the underlying type of the returned io.WriteCloser is
a *Writer.
TYPES
type Order int
Order specifies the bit ordering in an LZW data stream.
const (
LSB Order = iota
MSB
)
type Reader struct {
r io.ByteReader
bits uint32
nBits uint
width uint
err error
clear, eof, hi, overflow, last uint16
suffix [1 << maxWidth]uint8
prefix [1 << maxWidth]uint16
output [2 * 1 << maxWidth]byte
}
Reader is an io.Reader which can be used to read compressed data in the LZW
format.
func newReader(src io.Reader, order Order, litWidth int) *Reader
func (r *Reader) Close() error
Close closes the Reader and returns an error for any future read operation.
It does not close the underlying io.Reader.
func (r *Reader) Read(b []byte) (int, error)
Read implements io.Reader, reading uncompressed bytes from its underlying
Reader.
func (r *Reader) Reset(src io.Reader, order Order, litWidth int)
Reset clears the Reader's state and allows it to be reused again as a new
Reader.
func (r *Reader) decode()
decode decompresses bytes from r and leaves them in d.toRead. read specifies
how to decode bytes into codes. litWidth is the width in bits of literal
codes.
func (r *Reader) init(src io.Reader, order Order, litWidth int)
func (r *Reader) readLSB() (uint16, error)
readLSB returns the next code for "Least Significant Bits first" data.
func (r *Reader) readMSB() (uint16, error)
readMSB returns the next code for "Most Significant Bits first" data.
type Writer struct {
w writer
litWidth uint
order Order
write func(*Writer, uint32) error
nBits uint
width uint
bits uint32
hi, overflow uint32
savedCode uint32
err error
table [tableSize]uint32
}
Writer is an LZW compressor. It writes the compressed form of the data to an
underlying writer (see NewWriter).
func newWriter(dst io.Writer, order Order, litWidth int) *Writer
func (w *Writer) Close() error
Close closes the Writer, flushing any pending output. It does not close w's
underlying writer.
func (w *Writer) Reset(dst io.Writer, order Order, litWidth int)
Reset clears the Writer's state and allows it to be reused again as a new
Writer.
func (w *Writer) Write(p []byte) (n int, err error)
Write writes a compressed representation of p to w's underlying writer.
func (w *Writer) incHi() error
incHi increments e.hi and checks for both overflow and running out of unused
codes. In the latter case, incHi sends a clear code, resets the writer state
and returns errOutOfCodes.
func (w *Writer) init(dst io.Writer, order Order, litWidth int)
func (w *Writer) writeLSB(c uint32) error
writeLSB writes the code c for "Least Significant Bits first" data.
func (w *Writer) writeMSB(c uint32) error
writeMSB writes the code c for "Most Significant Bits first" data.
type writer interface {
io.ByteWriter
Flush() error
}
A writer is a buffered, flushable writer.
compress/zlib
func NewReader(r io.Reader) (io.ReadCloser, error)
NewReader creates a new ReadCloser. Reads from the returned ReadCloser
read and decompress data from r. If r does not implement io.ByteReader, the
decompressor may read more data than necessary from r. It is the caller's
responsibility to call Close on the ReadCloser when done.
The io.ReadCloser returned by NewReader also implements Resetter.
func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, error)
NewReaderDict is like NewReader but uses a preset dictionary. NewReaderDict
ignores the dictionary if the compressed data does not refer to it. If the
compressed data refers to a different dictionary, NewReaderDict returns
ErrDictionary.
The ReadCloser returned by NewReaderDict also implements Resetter.
TYPES
type Resetter interface {
Reset(r io.Reader, dict []byte) error
}
Resetter resets a ReadCloser returned by NewReader or NewReaderDict to
switch to a new underlying Reader. This permits reusing a ReadCloser instead
of allocating a new one.
type Writer struct {
w io.Writer
level int
dict []byte
compressor *flate.Writer
digest hash.Hash32
err error
scratch [4]byte
wroteHeader bool
}
A Writer takes data written to it and writes the compressed form of that
data to an underlying writer (see NewWriter).
func NewWriter(w io.Writer) *Writer
NewWriter creates a new Writer. Writes to the returned Writer are compressed
and written to w.
It is the caller's responsibility to call Close on the Writer when done.
Writes may be buffered and not flushed until Close.
func NewWriterLevel(w io.Writer, level int) (*Writer, error)
NewWriterLevel is like NewWriter but specifies the compression level instead
of assuming DefaultCompression.
The compression level can be DefaultCompression, NoCompression, HuffmanOnly
or any integer value between BestSpeed and BestCompression inclusive.
The error returned will be nil if the level is valid.
func NewWriterLevelDict(w io.Writer, level int, dict []byte) (*Writer, error)
NewWriterLevelDict is like NewWriterLevel but specifies a dictionary to
compress with.
The dictionary may be nil. If not, its contents should not be modified until
the Writer is closed.
func (z *Writer) Close() error
Close closes the Writer, flushing any unwritten data to the underlying
io.Writer, but does not close the underlying io.Writer.
func (z *Writer) Flush() error
Flush flushes the Writer to its underlying io.Writer.
func (z *Writer) Reset(w io.Writer)
Reset clears the state of the Writer z such that it is equivalent to its
initial state from NewWriterLevel or NewWriterLevelDict, but instead writing
to w.
func (z *Writer) Write(p []byte) (n int, err error)
Write writes a compressed form of p to the underlying io.Writer. The
compressed bytes are not necessarily flushed until the Writer is closed or
explicitly flushed.
func (z *Writer) writeHeader() (err error)
writeHeader writes the ZLIB header.
type reader struct {
r flate.Reader
decompressor io.ReadCloser
digest hash.Hash32
err error
scratch [4]byte
}
func (z *reader) Close() error
Calling Close does not close the wrapped io.Reader originally passed to
NewReader. In order for the ZLIB checksum to be verified, the reader must be
fully consumed until the io.EOF.
func (z *reader) Read(p []byte) (int, error)
func (z *reader) Reset(r io.Reader, dict []byte) error
container/heap
func Fix(h Interface, i int)
Fix re-establishes the heap ordering after the element at index i has
changed its value. Changing the value of the element at index i and then
calling Fix is equivalent to, but less expensive than, calling Remove(h,
i) followed by a Push of the new value. The complexity is O(log n) where n =
h.Len().
func Init(h Interface)
Init establishes the heap invariants required by the other routines in
this package. Init is idempotent with respect to the heap invariants and
may be called whenever the heap invariants may have been invalidated.
The complexity is O(n) where n = h.Len().
func Pop(h Interface) any
Pop removes and returns the minimum element (according to Less) from the
heap. The complexity is O(log n) where n = h.Len(). Pop is equivalent to
Remove(h, 0).
func Push(h Interface, x any)
Push pushes the element x onto the heap. The complexity is O(log n) where n
= h.Len().
func Remove(h Interface, i int) any
Remove removes and returns the element at index i from the heap. The
complexity is O(log n) where n = h.Len().
func down(h Interface, i0, n int) bool
func up(h Interface, j int)
TYPES
type Interface interface {
sort.Interface
}
The Interface type describes the requirements for a type using the routines
in this package. Any type that implements it may be used as a min-heap with
the following invariants (established after Init has been called or if the
data is empty or sorted):
!h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()
Note that Push and Pop in this interface are for package heap's
implementation to call. To add and remove things from the heap, use
heap.Push and heap.Pop.
container/list
container/ring
context
func AfterFunc(ctx Context, f func()) (stop func() bool)
AfterFunc arranges to call f in its own goroutine after ctx is done
(canceled or timed out). If ctx is already done, AfterFunc calls f
immediately in its own goroutine.
Multiple calls to AfterFunc on a context operate independently; one does not
replace another.
Calling the returned stop function stops the association of ctx with f.
It returns true if the call stopped f from being run. If stop returns false,
either the context is done and f has been started in its own goroutine;
or f was already stopped. The stop function does not wait for f to complete
before returning. If the caller needs to know whether f is completed,
it must coordinate with f explicitly.
If ctx has a "AfterFunc(func()) func() bool" method, AfterFunc will use it
to schedule the call.
func Cause(c Context) error
Cause returns a non-nil error explaining why c was canceled. The first
cancellation of c or one of its parents sets the cause. If that cancellation
happened via a call to CancelCauseFunc(err), then Cause returns err.
Otherwise Cause(c) returns the same value as c.Err(). Cause returns nil if c
has not been canceled yet.
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
WithCancel returns a derived context that points to the parent context but
has a new Done channel. The returned context's Done channel is closed when
the returned cancel function is called or when the parent context's Done
channel is closed, whichever happens first.
Canceling this context releases resources associated with it, so code should
call cancel as soon as the operations running in this Context complete.
func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)
WithCancelCause behaves like WithCancel but returns a CancelCauseFunc
instead of a CancelFunc. Calling cancel with a non-nil error (the "cause")
records that error in ctx; it can then be retrieved using Cause(ctx).
Calling cancel with nil sets the cause to Canceled.
Example use:
ctx, cancel := context.WithCancelCause(parent)
cancel(myError)
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
WithDeadline returns a derived context that points to the parent context but
has the deadline adjusted to be no later than d. If the parent's deadline is
already earlier than d, WithDeadline(parent, d) is semantically equivalent
to parent. The returned [Context.Done] channel is closed when the deadline
expires, when the returned cancel function is called, or when the parent
context's Done channel is closed, whichever happens first.
Canceling this context releases resources associated with it, so code should
call cancel as soon as the operations running in this Context complete.
func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)
WithDeadlineCause behaves like WithDeadline but also sets the cause of the
returned Context when the deadline is exceeded. The returned CancelFunc does
not set the cause.
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
Canceling this context releases resources associated with it, so code should
call cancel as soon as the operations running in this Context complete:
func slowOperationWithTimeout(ctx context.Context) (Result, error) {
ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
return slowOperation(ctx)
}
func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)
WithTimeoutCause behaves like WithTimeout but also sets the cause of the
returned Context when the timeout expires. The returned CancelFunc does not
set the cause.
func contextName(c Context) string
func init()
func removeChild(parent Context, child canceler)
removeChild removes a context from its parent.
func stringify(v any) string
stringify tries a bit to stringify v, without using fmt, since we don't
want context depending on the unicode tables. This is only used by
*valueCtx.String().
func value(c Context, key any) any
TYPES
type CancelCauseFunc func(cause error)
A CancelCauseFunc behaves like a CancelFunc but additionally sets the
cancellation cause. This cause can be retrieved by calling Cause on the
canceled Context or on any of its derived Contexts.
If the context has already been canceled, CancelCauseFunc does not set the
cause. For example, if childContext is derived from parentContext:
- if parentContext is canceled with cause1 before childContext is canceled
with cause2, then Cause(parentContext) == Cause(childContext) == cause1
- if childContext is canceled with cause2 before parentContext is canceled
with cause1, then Cause(parentContext) == cause1 and Cause(childContext)
== cause2
type CancelFunc func()
A CancelFunc tells an operation to abandon its work. A CancelFunc does not
wait for the work to stop. A CancelFunc may be called by multiple goroutines
simultaneously. After the first call, subsequent calls to a CancelFunc do
nothing.
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key any) any
}
A Context carries a deadline, a cancellation signal, and other values across
API boundaries.
Context's methods may be called by multiple goroutines simultaneously.
func Background() Context
Background returns a non-nil, empty Context. It is never canceled, has no
values, and has no deadline. It is typically used by the main function,
initialization, and tests, and as the top-level Context for incoming
requests.
func TODO() Context
TODO returns a non-nil, empty Context. Code should use context.TODO when
it's unclear which Context to use or it is not yet available (because
the surrounding function has not yet been extended to accept a Context
parameter).
func WithValue(parent Context, key, val any) Context
WithValue returns a derived context that points to the parent Context.
In the derived context, the value associated with key is val.
Use context Values only for request-scoped data that transits processes and
APIs, not for passing optional parameters to functions.
The provided key must be comparable and should not be of type string or any
other built-in type to avoid collisions between packages using context.
Users of WithValue should define their own types for keys. To avoid
allocating when assigning to an interface{}, context keys often have
concrete type struct{}. Alternatively, exported context key variables'
static type should be a pointer or interface.
func WithoutCancel(parent Context) Context
WithoutCancel returns a derived context that points to the parent context
and is not canceled when parent is canceled. The returned context returns no
Deadline or Err, and its Done channel is nil. Calling Cause on the returned
context returns nil.
type afterFuncCtx struct {
cancelCtx
f func()
}
func (c *afterFuncCtx) Done() <-chan struct{}
func (c *afterFuncCtx) Err() error
func (c *afterFuncCtx) String() string
func (c *afterFuncCtx) Value(key any) any
func (a *afterFuncCtx) cancel(removeFromParent bool, err, cause error)
func (c *afterFuncCtx) propagateCancel(parent Context, child canceler)
propagateCancel arranges for child to be canceled when parent is. It sets
the parent context of cancelCtx.
type afterFuncer interface {
AfterFunc(func()) func() bool
}
type backgroundCtx struct{ emptyCtx }
func (backgroundCtx) Deadline() (deadline time.Time, ok bool)
func (backgroundCtx) Done() <-chan struct{}
func (backgroundCtx) Err() error
func (backgroundCtx) String() string
func (backgroundCtx) Value(key any) any
type cancelCtx struct {
Context
}
A cancelCtx can be canceled. When canceled, it also cancels any children
that implement canceler.
func parentCancelCtx(parent Context) (*cancelCtx, bool)
parentCancelCtx returns the underlying *cancelCtx for parent. It does this
by looking up parent.Value(&cancelCtxKey) to find the innermost enclosing
*cancelCtx and then checking whether parent.Done() matches that *cancelCtx.
(If not, the *cancelCtx has been wrapped in a custom implementation
providing a different done channel, in which case we should not bypass it.)
func withCancel(parent Context) *cancelCtx
func (c *cancelCtx) Done() <-chan struct{}
func (c *cancelCtx) Err() error
func (c *cancelCtx) String() string
func (c *cancelCtx) Value(key any) any
func (c *cancelCtx) cancel(removeFromParent bool, err, cause error)
cancel closes c.done, cancels each of c's children, and, if removeFromParent
is true, removes c from its parent's children. cancel sets c.cause to cause
if this is the first time c is canceled.
func (c *cancelCtx) propagateCancel(parent Context, child canceler)
propagateCancel arranges for child to be canceled when parent is. It sets
the parent context of cancelCtx.
type canceler interface {
cancel(removeFromParent bool, err, cause error)
Done() <-chan struct{}
}
A canceler is a context type that can be canceled directly. The
implementations are *cancelCtx and *timerCtx.
type deadlineExceededError struct{}
func (deadlineExceededError) Error() string
func (deadlineExceededError) Temporary() bool
func (deadlineExceededError) Timeout() bool
type emptyCtx struct{}
An emptyCtx is never canceled, has no values, and has no deadline. It is the
common base of backgroundCtx and todoCtx.
func (emptyCtx) Deadline() (deadline time.Time, ok bool)
func (emptyCtx) Done() <-chan struct{}
func (emptyCtx) Err() error
func (emptyCtx) Value(key any) any
type stopCtx struct {
Context
stop func() bool
}
A stopCtx is used as the parent context of a cancelCtx when an AfterFunc
has been registered with the parent. It holds the stop function used to
unregister the AfterFunc.
type stringer interface {
String() string
}
type timerCtx struct {
cancelCtx
deadline time.Time
}
A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
implement Done and Err. It implements cancel by stopping its timer then
delegating to cancelCtx.cancel.
func (c *timerCtx) Deadline() (deadline time.Time, ok bool)
func (c *timerCtx) Done() <-chan struct{}
func (c *timerCtx) Err() error
func (c *timerCtx) String() string
func (c *timerCtx) Value(key any) any
func (c *timerCtx) cancel(removeFromParent bool, err, cause error)
func (c *timerCtx) propagateCancel(parent Context, child canceler)
propagateCancel arranges for child to be canceled when parent is. It sets
the parent context of cancelCtx.
type todoCtx struct{ emptyCtx }
func (todoCtx) Deadline() (deadline time.Time, ok bool)
func (todoCtx) Done() <-chan struct{}
func (todoCtx) Err() error
func (todoCtx) String() string
func (todoCtx) Value(key any) any
type valueCtx struct {
Context
key, val any
}
A valueCtx carries a key-value pair. It implements Value for that key and
delegates all other calls to the embedded Context.
func (c *valueCtx) String() string
func (c *valueCtx) Value(key any) any
type withoutCancelCtx struct {
c Context
}
func (withoutCancelCtx) Deadline() (deadline time.Time, ok bool)
func (withoutCancelCtx) Done() <-chan struct{}
func (withoutCancelCtx) Err() error
func (c withoutCancelCtx) String() string
func (c withoutCancelCtx) Value(key any) any
crypto
func RegisterHash(h Hash, f func() hash.Hash)
RegisterHash registers a function that returns a new instance of the given
hash function. This is intended to be called from the init function in
packages that implement hash functions.
TYPES
type Decrypter interface {
Public() PublicKey
Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
}
Decrypter is an interface for an opaque private key that can be used for
asymmetric decryption operations. An example would be an RSA key kept in a
hardware module.
type DecrypterOpts any
type Hash uint
Hash identifies a cryptographic hash function that is implemented in another
package.
const (
maxHash
)
func (h Hash) Available() bool
Available reports whether the given hash function is linked into the binary.
func (h Hash) HashFunc() Hash
HashFunc simply returns the value of h so that Hash implements SignerOpts.
func (h Hash) New() hash.Hash
New returns a new hash.Hash calculating the given hash function. New panics
if the hash function is not linked into the binary.
func (h Hash) Size() int
Size returns the length, in bytes, of a digest resulting from the given hash
function. It doesn't require that the hash function in question be linked
into the program.
func (h Hash) String() string
type PrivateKey any
PrivateKey represents a private key using an unspecified algorithm.
Although this type is an empty interface for backwards compatibility
reasons, all private key types in the standard library implement the
following interface
interface{
Public() crypto.PublicKey
Equal(x crypto.PrivateKey) bool
}
as well as purpose-specific interfaces such as Signer and Decrypter,
which can be used for increased type safety within applications.
type PublicKey any
PublicKey represents a public key using an unspecified algorithm.
Although this type is an empty interface for backwards compatibility
reasons, all public key types in the standard library implement the
following interface
interface{
Equal(x crypto.PublicKey) bool
}
which can be used for increased type safety within applications.
type Signer interface {
Public() PublicKey
Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
}
Signer is an interface for an opaque private key that can be used for
signing operations. For example, an RSA key kept in a hardware module.
type SignerOpts interface {
HashFunc() Hash
}
SignerOpts contains options for signing with a Signer.
crypto/aes
func NewCipher(key []byte) (cipher.Block, error)
NewCipher creates and returns a new cipher.Block. The key argument should
be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192,
or AES-256.
TYPES
type KeySizeError int
func (k KeySizeError) Error() string
crypto/boring
func Enabled() bool
Enabled reports whether BoringCrypto handles supported crypto operations.
crypto/cipher
func deriveCounter(H, counter *[gcmBlockSize]byte, nonce []byte)
func gcmAuth(out []byte, H, tagMask *[gcmBlockSize]byte, ciphertext, additionalData []byte)
func gcmCounterCryptGeneric(b Block, out, src []byte, counter *[gcmBlockSize]byte)
func gcmInc32(counterBlock *[gcmBlockSize]byte)
func sliceForAppend(in []byte, n int) (head, tail []byte)
sliceForAppend takes a slice and a requested number of bytes. It returns a
slice with the contents of the given slice followed by that many bytes and a
second slice that aliases into it and contains only the extra bytes. If the
original slice has sufficient capacity then no allocation is performed.
TYPES
type AEAD interface {
NonceSize() int
Overhead() int
Seal(dst, nonce, plaintext, additionalData []byte) []byte
Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
}
AEAD is a cipher mode providing authenticated encryption with
associated data. For a description of the methodology, see
func NewGCM(cipher Block) (AEAD, error)
NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter
Mode with the standard nonce length.
In general, the GHASH operation performed by this implementation of GCM is
not constant-time. An exception is when the underlying Block was created by
aes.NewCipher on systems with hardware support for AES. See the crypto/aes
package documentation for details.
func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)
NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in
Galois Counter Mode, which accepts nonces of the given length. The length
must not be zero.
Only use this function if you require compatibility with an existing
cryptosystem that uses non-standard nonce lengths. All other users should
use NewGCM, which is faster and more resistant to misuse.
func NewGCMWithRandomNonce(cipher Block) (AEAD, error)
NewGCMWithRandomNonce returns the given cipher wrapped in Galois Counter
Mode, with randomly-generated nonces. The cipher must have been created by
aes.NewCipher.
It generates a random 96-bit nonce, which is prepended to the ciphertext
by Seal, and is extracted from the ciphertext by Open. The NonceSize of the
AEAD is zero, while the Overhead is 28 bytes (the combination of nonce size
and tag size).
A given key MUST NOT be used to encrypt more than 2^32 messages, to limit
the risk of a random nonce collision to negligible levels.
func NewGCMWithTagSize(cipher Block, tagSize int) (AEAD, error)
NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois
Counter Mode, which generates tags with the given length.
Tag sizes between 12 and 16 bytes are allowed.
Only use this function if you require compatibility with an existing
cryptosystem that uses non-standard tag lengths. All other users should use
NewGCM, which is more resistant to misuse.
func newGCM(cipher Block, nonceSize, tagSize int) (AEAD, error)
func newGCMFallback(cipher Block, nonceSize, tagSize int) (AEAD, error)
type Block interface {
BlockSize() int
Encrypt(dst, src []byte)
Decrypt(dst, src []byte)
}
A Block represents an implementation of block cipher using a given key.
It provides the capability to encrypt or decrypt individual blocks. The mode
implementations extend that capability to streams of blocks.
type BlockMode interface {
BlockSize() int
CryptBlocks(dst, src []byte)
}
A BlockMode represents a block cipher running in a block-based mode (CBC,
ECB etc).
func NewCBCDecrypter(b Block, iv []byte) BlockMode
NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining
mode, using the given Block. The length of iv must be the same as the
Block's block size and must match the iv used to encrypt the data.
func NewCBCEncrypter(b Block, iv []byte) BlockMode
NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining
mode, using the given Block. The length of iv must be the same as the
Block's block size.
func newCBCGenericDecrypter(b Block, iv []byte) BlockMode
newCBCGenericDecrypter returns a BlockMode which encrypts in cipher block
chaining mode, using the given Block. The length of iv must be the same as
the Block's block size. This always returns the generic non-asm decrypter
for use in fuzz testing.
func newCBCGenericEncrypter(b Block, iv []byte) BlockMode
newCBCGenericEncrypter returns a BlockMode which encrypts in cipher block
chaining mode, using the given Block. The length of iv must be the same as
the Block's block size. This always returns the generic non-asm encrypter
for use in fuzz testing.
type Stream interface {
XORKeyStream(dst, src []byte)
}
A Stream represents a stream cipher.
func NewCFBDecrypter(block Block, iv []byte) Stream
NewCFBDecrypter returns a Stream which decrypts with cipher feedback mode,
using the given Block. The iv must be the same length as the Block's block
size.
Deprecated: CFB mode is not authenticated, which generally enables active
attacks to manipulate and recover the plaintext. It is recommended that
applications use AEAD modes instead. The standard library implementation of
CFB is also unoptimized and not validated as part of the FIPS 140-3 module.
If an unauthenticated Stream mode is required, use NewCTR instead.
func NewCFBEncrypter(block Block, iv []byte) Stream
NewCFBEncrypter returns a Stream which encrypts with cipher feedback mode,
using the given Block. The iv must be the same length as the Block's block
size.
Deprecated: CFB mode is not authenticated, which generally enables active
attacks to manipulate and recover the plaintext. It is recommended that
applications use AEAD modes instead. The standard library implementation of
CFB is also unoptimized and not validated as part of the FIPS 140-3 module.
If an unauthenticated Stream mode is required, use NewCTR instead.
func NewCTR(block Block, iv []byte) Stream
NewCTR returns a Stream which encrypts/decrypts using the given Block in
counter mode. The length of iv must be the same as the Block's block size.
func NewOFB(b Block, iv []byte) Stream
NewOFB returns a Stream that encrypts or decrypts using the block cipher b
in output feedback mode. The initialization vector iv's length must be equal
to b's block size.
Deprecated: OFB mode is not authenticated, which generally enables active
attacks to manipulate and recover the plaintext. It is recommended that
applications use AEAD modes instead. The standard library implementation of
OFB is also unoptimized and not validated as part of the FIPS 140-3 module.
If an unauthenticated Stream mode is required, use NewCTR instead.
func newCFB(block Block, iv []byte, decrypt bool) Stream
type StreamReader struct {
S Stream
R io.Reader
}
StreamReader wraps a Stream into an io.Reader. It calls XORKeyStream to
process each slice of data which passes through.
func (r StreamReader) Read(dst []byte) (n int, err error)
type StreamWriter struct {
S Stream
W io.Writer
}
StreamWriter wraps a Stream into an io.Writer. It calls XORKeyStream to
process each slice of data which passes through. If any StreamWriter.Write
call returns short then the StreamWriter is out of sync and must be
discarded. A StreamWriter has no internal buffering; StreamWriter.Close does
not need to be called to flush write data.
func (w StreamWriter) Close() error
Close closes the underlying Writer and returns its Close return value,
if the Writer is also an io.Closer. Otherwise it returns nil.
func (w StreamWriter) Write(src []byte) (n int, err error)
type aesCtrWrapper struct {
c *aes.CTR
}
aesCtrWrapper hides extra methods from aes.CTR.
func (x aesCtrWrapper) XORKeyStream(dst, src []byte)
type cbc struct {
b Block
blockSize int
iv []byte
tmp []byte
}
func newCBC(b Block, iv []byte) *cbc
type cbcDecAble interface {
NewCBCDecrypter(iv []byte) BlockMode
}
cbcDecAble is an interface implemented by ciphers that have a specific
optimized implementation of CBC decryption. crypto/aes doesn't use this
anymore, and we'd like to eventually remove it.
type cbcDecrypter cbc
func (x *cbcDecrypter) BlockSize() int
func (x *cbcDecrypter) CryptBlocks(dst, src []byte)
func (x *cbcDecrypter) SetIV(iv []byte)
type cbcEncAble interface {
NewCBCEncrypter(iv []byte) BlockMode
}
cbcEncAble is an interface implemented by ciphers that have a specific
optimized implementation of CBC encryption. crypto/aes doesn't use this
anymore, and we'd like to eventually remove it.
type cbcEncrypter cbc
func (x *cbcEncrypter) BlockSize() int
func (x *cbcEncrypter) CryptBlocks(dst, src []byte)
func (x *cbcEncrypter) SetIV(iv []byte)
type cfb struct {
b Block
next []byte
out []byte
outUsed int
decrypt bool
}
func (x *cfb) XORKeyStream(dst, src []byte)
type ctr struct {
b Block
ctr []byte
out []byte
outUsed int
}
func (x *ctr) XORKeyStream(dst, src []byte)
func (x *ctr) refill()
type ctrAble interface {
NewCTR(iv []byte) Stream
}
ctrAble is an interface implemented by ciphers that have a specific
optimized implementation of CTR. crypto/aes doesn't use this anymore,
and we'd like to eventually remove it.
type gcmAble interface {
NewGCM(nonceSize, tagSize int) (AEAD, error)
}
gcmAble is an interface implemented by ciphers that have a specific
optimized implementation of GCM. crypto/aes doesn't use this anymore,
and we'd like to eventually remove it.
type gcmFallback struct {
cipher Block
nonceSize int
tagSize int
}
gcmFallback is only used for non-AES ciphers, which regrettably we
theoretically support. It's a copy of the generic implementation from
crypto/internal/fips140/aes/gcm/gcm_generic.go, refer to that file for more
details.
func (g *gcmFallback) NonceSize() int
func (g *gcmFallback) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
func (g *gcmFallback) Overhead() int
func (g *gcmFallback) Seal(dst, nonce, plaintext, additionalData []byte) []byte
type gcmWithRandomNonce struct {
*gcm.GCM
}
func (g gcmWithRandomNonce) NonceSize() int
func (g gcmWithRandomNonce) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
func (g gcmWithRandomNonce) Overhead() int
func (g gcmWithRandomNonce) Seal(dst, nonce, plaintext, additionalData []byte) []byte
type ofb struct {
b Block
cipher []byte
out []byte
outUsed int
}
func (x *ofb) XORKeyStream(dst, src []byte)
func (x *ofb) refill()
crypto/des
func NewCipher(key []byte) (cipher.Block, error)
NewCipher creates and returns a new cipher.Block.
func NewTripleDESCipher(key []byte) (cipher.Block, error)
NewTripleDESCipher creates and returns a new cipher.Block.
func cryptBlock(subkeys []uint64, dst, src []byte, decrypt bool)
func feistel(l, r uint32, k0, k1 uint64) (lout, rout uint32)
DES Feistel function. feistelBox must be initialized via
feistelBoxOnce.Do(initFeistelBox) first.
func initFeistelBox()
func ksRotate(in uint32) (out []uint32)
creates 16 28-bit blocks rotated according to the rotation schedule.
func permuteBlock(src uint64, permutation []uint8) (block uint64)
general purpose function to perform DES block permutations.
func permuteFinalBlock(block uint64) uint64
permuteFinalBlock is equivalent to the permutation defined by
finalPermutation.
func permuteInitialBlock(block uint64) uint64
permuteInitialBlock is equivalent to the permutation defined by
initialPermutation.
func unpack(x uint64) uint64
Expand 48-bit input to 64-bit, with each 6-bit block padded by extra two
bits at the top. By doing so, we can have the input blocks (four bits
each), and the key blocks (six bits each) well-aligned without extra
shifts/rotations for alignments.
TYPES
type KeySizeError int
func (k KeySizeError) Error() string
type desCipher struct {
subkeys [16]uint64
}
desCipher is an instance of DES encryption.
func (c *desCipher) BlockSize() int
func (c *desCipher) Decrypt(dst, src []byte)
func (c *desCipher) Encrypt(dst, src []byte)
func (c *desCipher) generateSubkeys(keyBytes []byte)
creates 16 56-bit subkeys from the original key.
type tripleDESCipher struct {
cipher1, cipher2, cipher3 desCipher
}
A tripleDESCipher is an instance of TripleDES encryption.
func (c *tripleDESCipher) BlockSize() int
func (c *tripleDESCipher) Decrypt(dst, src []byte)
func (c *tripleDESCipher) Encrypt(dst, src []byte)
crypto/dsa
func GenerateKey(priv *PrivateKey, rand io.Reader) error
GenerateKey generates a public&private key pair. The Parameters of the
PrivateKey must already be valid (see GenerateParameters).
func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) error
GenerateParameters puts a random, valid set of DSA parameters into params.
This function can take many seconds, even on fast machines.
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)
Sign signs an arbitrary length hash (which should be the result of hashing
a larger message) using the private key, priv. It returns the signature as a
pair of integers. The security of the private key depends on the entropy of
rand.
Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated
to the byte-length of the subgroup. This function does not perform that
truncation itself.
Be aware that calling Sign with an attacker-controlled PrivateKey may
require an arbitrary amount of CPU.
func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool
Verify verifies the signature in r, s of hash using the public key, pub.
It reports whether the signature is valid.
Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated
to the byte-length of the subgroup. This function does not perform that
truncation itself.
func fermatInverse(k, P *big.Int) *big.Int
fermatInverse calculates the inverse of k in GF(P) using Fermat's method.
This has better constant-time properties than Euclid's method (implemented
in math/big.Int.ModInverse) although math/big itself isn't strictly
constant-time so it's not perfect.
TYPES
type ParameterSizes int
ParameterSizes is an enumeration of the acceptable bit lengths of the primes
in a set of DSA parameters. See FIPS 186-3, section 4.2.
const (
L1024N160 ParameterSizes = iota
L2048N224
L2048N256
L3072N256
)
type Parameters struct {
P, Q, G *big.Int
}
Parameters represents the domain parameters for a key. These parameters can
be shared across many keys. The bit length of Q must be a multiple of 8.
type PrivateKey struct {
PublicKey
X *big.Int
}
PrivateKey represents a DSA private key.
type PublicKey struct {
Parameters
Y *big.Int
}
PublicKey represents a DSA public key.
crypto/ecdh
func isZero(x []byte) bool
isZero reports whether x is all zeroes in constant time.
func x25519ScalarMult(dst, scalar, point []byte)
TYPES
type Curve interface {
GenerateKey(rand io.Reader) (*PrivateKey, error)
NewPrivateKey(key []byte) (*PrivateKey, error)
NewPublicKey(key []byte) (*PublicKey, error)
ecdh(local *PrivateKey, remote *PublicKey) ([]byte, error)
}
func P256() Curve
P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section
D.2.3), also known as secp256r1 or prime256v1.
Multiple invocations of this function will return the same value, which can
be used for equality checks and switch statements.
func P384() Curve
P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section
D.2.4), also known as secp384r1.
Multiple invocations of this function will return the same value, which can
be used for equality checks and switch statements.
func P521() Curve
P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section
D.2.5), also known as secp521r1.
Multiple invocations of this function will return the same value, which can
be used for equality checks and switch statements.
func X25519() Curve
X25519 returns a Curve which implements the X25519 function over Curve25519
(RFC 7748, Section 5).
Multiple invocations of this function will return the same value, so it can
be used for equality checks and switch statements.
type PrivateKey struct {
curve Curve
privateKey []byte
publicKey *PublicKey
boring *boring.PrivateKeyECDH
fips *ecdh.PrivateKey
}
PrivateKey is an ECDH private key, usually kept secret.
These keys can be parsed with crypto/x509.ParsePKCS8PrivateKey and encoded
with crypto/x509.MarshalPKCS8PrivateKey. For NIST curves, they then need to
be converted with crypto/ecdsa.PrivateKey.ECDH after parsing.
func (k *PrivateKey) Bytes() []byte
Bytes returns a copy of the encoding of the private key.
func (k *PrivateKey) Curve() Curve
func (k *PrivateKey) ECDH(remote *PublicKey) ([]byte, error)
ECDH performs an ECDH exchange and returns the shared secret. The PrivateKey
and PublicKey must use the same curve.
For NIST curves, this performs ECDH as specified in SEC 1, Version 2.0,
Section 3.3.1, and returns the x-coordinate encoded according to SEC 1,
Version 2.0, Section 2.3.5. The result is never the point at infinity.
This is also known as the Shared Secret Computation of the Ephemeral Unified
Model scheme specified in NIST SP 800-56A Rev. 3, Section 6.1.2.2.
For X25519, this performs ECDH as specified in RFC 7748, Section 6.1.
If the result is the all-zero value, ECDH returns an error.
func (k *PrivateKey) Equal(x crypto.PrivateKey) bool
Equal returns whether x represents the same private key as k.
Note that there can be equivalent private keys with different encodings
which would return false from this check but behave the same way as inputs
to [ECDH].
This check is performed in constant time as long as the key types and their
curve match.
func (k *PrivateKey) Public() crypto.PublicKey
Public implements the implicit interface of all standard library private
keys. See the docs of crypto.PrivateKey.
func (k *PrivateKey) PublicKey() *PublicKey
type PublicKey struct {
curve Curve
publicKey []byte
boring *boring.PublicKeyECDH
fips *ecdh.PublicKey
}
PublicKey is an ECDH public key, usually a peer's ECDH share sent over the
wire.
These keys can be parsed with crypto/x509.ParsePKIXPublicKey and encoded
with crypto/x509.MarshalPKIXPublicKey. For NIST curves, they then need to be
converted with crypto/ecdsa.PublicKey.ECDH after parsing.
func (k *PublicKey) Bytes() []byte
Bytes returns a copy of the encoding of the public key.
func (k *PublicKey) Curve() Curve
func (k *PublicKey) Equal(x crypto.PublicKey) bool
Equal returns whether x represents the same public key as k.
Note that there can be equivalent public keys with different encodings which
would return false from this check but behave the same way as inputs to
ECDH.
This check is performed in constant time as long as the key types and their
curve match.
type nistCurve struct {
name string
generate func(io.Reader) (*ecdh.PrivateKey, error)
newPrivateKey func([]byte) (*ecdh.PrivateKey, error)
newPublicKey func(publicKey []byte) (*ecdh.PublicKey, error)
sharedSecret func(*ecdh.PrivateKey, *ecdh.PublicKey) (sharedSecret []byte, err error)
}
func (c *nistCurve) GenerateKey(rand io.Reader) (*PrivateKey, error)
func (c *nistCurve) NewPrivateKey(key []byte) (*PrivateKey, error)
func (c *nistCurve) NewPublicKey(key []byte) (*PublicKey, error)
func (c *nistCurve) String() string
func (c *nistCurve) ecdh(local *PrivateKey, remote *PublicKey) ([]byte, error)
type x25519Curve struct{}
func (c *x25519Curve) GenerateKey(rand io.Reader) (*PrivateKey, error)
func (c *x25519Curve) NewPrivateKey(key []byte) (*PrivateKey, error)
func (c *x25519Curve) NewPublicKey(key []byte) (*PublicKey, error)
func (c *x25519Curve) String() string
func (c *x25519Curve) ecdh(local *PrivateKey, remote *PublicKey) ([]byte, error)
crypto/ecdsa
func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)
Sign signs a hash (which should be the result of hashing a larger message)
using the private key, priv. If the hash is longer than the bit-length of
the private key's curve order, the hash will be truncated to that length.
It returns the signature as a pair of integers. Most applications should use
SignASN1 instead of dealing directly with r, s.
func SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error)
SignASN1 signs a hash (which should be the result of hashing a larger
message) using the private key, priv. If the hash is longer than the
bit-length of the private key's curve order, the hash will be truncated to
that length. It returns the ASN.1 encoded signature.
The signature is randomized. Most applications should use crypto/rand.Reader
as rand. Note that the returned signature does not depend deterministically
on the bytes read from rand, and may change between calls and/or between
versions.
func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool
Verify verifies the signature in r, s of hash using the public key, pub.
Its return value records whether the signature is valid. Most applications
should use VerifyASN1 instead of dealing directly with r, s.
The inputs are not considered confidential, and may leak through timing side
channels, or if an attacker has control of part of the inputs.
func VerifyASN1(pub *PublicKey, hash, sig []byte) bool
VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the
public key, pub. Its return value records whether the signature is valid.
The inputs are not considered confidential, and may leak through timing side
channels, or if an attacker has control of part of the inputs.
func addASN1IntBytes(b *cryptobyte.Builder, bytes []byte)
addASN1IntBytes encodes in ASN.1 a positive integer represented as a
big-endian byte slice with zero or more leading zeroes.
func bigIntEqual(a, b *big.Int) bool
bigIntEqual reports whether a and b are equal leaking only their bit length
through timing side-channels.
func boringPrivateKey(priv *PrivateKey) (*boring.PrivateKeyECDSA, error)
func boringPublicKey(pub *PublicKey) (*boring.PublicKeyECDSA, error)
func curveToECDH(c elliptic.Curve) ecdh.Curve
func encodeSignature(r, s []byte) ([]byte, error)
func hashToInt(hash []byte, c elliptic.Curve) *big.Int
hashToInt converts a hash value to an integer. Per FIPS 186-4, Section 6.4,
we use the left-most bits of the hash to match the bit-length of the order
of the curve. This also performs Step 5 of SEC 1, Version 2.0, Section
4.1.3.
func init()
func parseSignature(sig []byte) (r, s []byte, err error)
func pointFromAffine(curve elliptic.Curve, x, y *big.Int) ([]byte, error)
pointFromAffine is used to convert the PublicKey to a nistec SetBytes input.
func pointToAffine(curve elliptic.Curve, p []byte) (x, y *big.Int, err error)
pointToAffine is used to convert a nistec Bytes encoding to a PublicKey.
func privateKeyEqual(k1, k2 *PrivateKey) bool
func privateKeyToFIPS[P ecdsa.Point[P]](c *ecdsa.Curve[P], priv *PrivateKey) (*ecdsa.PrivateKey, error)
func publicKeyEqual(k1, k2 *PublicKey) bool
func publicKeyToFIPS[P ecdsa.Point[P]](c *ecdsa.Curve[P], pub *PublicKey) (*ecdsa.PublicKey, error)
func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error)
randFieldElement returns a random element of the order of the given curve
using the procedure given in FIPS 186-4, Appendix B.5.2.
func signFIPS[P ecdsa.Point[P]](c *ecdsa.Curve[P], priv *PrivateKey, rand io.Reader, hash []byte) ([]byte, error)
func signFIPSDeterministic[P ecdsa.Point[P]](c *ecdsa.Curve[P], hashFunc crypto.Hash, priv *PrivateKey, hash []byte) ([]byte, error)
func signLegacy(priv *PrivateKey, csprng io.Reader, hash []byte) (sig []byte, err error)
func signRFC6979(priv *PrivateKey, hash []byte, opts crypto.SignerOpts) ([]byte, error)
func verifyFIPS[P ecdsa.Point[P]](c *ecdsa.Curve[P], pub *PublicKey, hash, sig []byte) bool
func verifyLegacy(pub *PublicKey, hash []byte, sig []byte) bool
TYPES
type PrivateKey struct {
PublicKey
D *big.Int
}
PrivateKey represents an ECDSA private key.
func GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error)
GenerateKey generates a new ECDSA private key for the specified curve.
Most applications should use crypto/rand.Reader as rand. Note that the
returned key does not depend deterministically on the bytes read from rand,
and may change between calls and/or between versions.
func copyPrivateKey(k *PrivateKey) PrivateKey
func generateFIPS[P ecdsa.Point[P]](curve elliptic.Curve, c *ecdsa.Curve[P], rand io.Reader) (*PrivateKey, error)
func generateLegacy(c elliptic.Curve, rand io.Reader) (*PrivateKey, error)
func privateKeyFromFIPS(curve elliptic.Curve, priv *ecdsa.PrivateKey) (*PrivateKey, error)
func (k *PrivateKey) ECDH() (*ecdh.PrivateKey, error)
ECDH returns k as a ecdh.PrivateKey. It returns an error if the key is
invalid according to the definition of ecdh.Curve.NewPrivateKey, or if the
Curve is not supported by crypto/ecdh.
func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool
Equal reports whether priv and x have the same value.
See PublicKey.Equal for details on how Curve is compared.
func (priv *PrivateKey) Public() crypto.PublicKey
Public returns the public key corresponding to priv.
func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
Sign signs a hash (which should be the result of hashing a larger message
with opts.HashFunc()) using the private key, priv. If the hash is longer
than the bit-length of the private key's curve order, the hash will be
truncated to that length. It returns the ASN.1 encoded signature, like
SignASN1.
If rand is not nil, the signature is randomized. Most applications should
use crypto/rand.Reader as rand. Note that the returned signature does not
depend deterministically on the bytes read from rand, and may change between
calls and/or between versions.
If rand is nil, Sign will produce a deterministic signature according to RFC
6979. When producing a deterministic signature, opts.HashFunc() must be the
function used to produce digest and priv.Curve must be one of elliptic.P224,
elliptic.P256, elliptic.P384, or elliptic.P521.
type PublicKey struct {
elliptic.Curve
X, Y *big.Int
}
PublicKey represents an ECDSA public key.
func copyPublicKey(k *PublicKey) PublicKey
func publicKeyFromFIPS(curve elliptic.Curve, pub *ecdsa.PublicKey) (*PublicKey, error)
func (k *PublicKey) ECDH() (*ecdh.PublicKey, error)
ECDH returns k as a ecdh.PublicKey. It returns an error if the key is
invalid according to the definition of ecdh.Curve.NewPublicKey, or if the
Curve is not supported by crypto/ecdh.
func (pub *PublicKey) Equal(x crypto.PublicKey) bool
Equal reports whether pub and x have the same value.
Two keys are only considered to have the same value if they have
the same Curve value. Note that for example elliptic.P256 and
elliptic.P256().Params() are different values, as the latter is a generic
not constant time implementation.
type boringPriv struct {
key *boring.PrivateKeyECDSA
orig PrivateKey
}
type boringPub struct {
key *boring.PublicKeyECDSA
orig PublicKey
}
crypto/ed25519
func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error)
GenerateKey generates a public/private key pair using entropy from rand.
If rand is nil, crypto/rand.Reader will be used.
The output of this function is deterministic, and equivalent to reading
SeedSize bytes from rand, and passing them to NewKeyFromSeed.
func Sign(privateKey PrivateKey, message []byte) []byte
Sign signs the message with privateKey and returns a signature. It will
panic if len(privateKey) is not PrivateKeySize.
func Verify(publicKey PublicKey, message, sig []byte) bool
Verify reports whether sig is a valid signature of message by publicKey.
It will panic if len(publicKey) is not PublicKeySize.
The inputs are not considered confidential, and may leak through timing side
channels, or if an attacker has control of part of the inputs.
func VerifyWithOptions(publicKey PublicKey, message, sig []byte, opts *Options) error
VerifyWithOptions reports whether sig is a valid signature of message by
publicKey. A valid signature is indicated by returning a nil error. It will
panic if len(publicKey) is not PublicKeySize.
If opts.Hash is crypto.SHA512, the pre-hashed variant Ed25519ph is used
and message is expected to be a SHA-512 hash, otherwise opts.Hash must be
crypto.Hash(0) and the message must not be hashed, as Ed25519 performs two
passes over messages to be signed.
The inputs are not considered confidential, and may leak through timing side
channels, or if an attacker has control of part of the inputs.
func newKeyFromSeed(privateKey, seed []byte)
func sign(signature []byte, privateKey PrivateKey, message []byte)
TYPES
type Options struct {
Hash crypto.Hash
Context string
}
Options can be used with PrivateKey.Sign or VerifyWithOptions to select
Ed25519 variants.
func (o *Options) HashFunc() crypto.Hash
HashFunc returns o.Hash.
type PrivateKey []byte
PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer.
func NewKeyFromSeed(seed []byte) PrivateKey
NewKeyFromSeed calculates a private key from a seed. It will panic if
len(seed) is not SeedSize. This function is provided for interoperability
with RFC 8032. RFC 8032's private keys correspond to seeds in this package.
func (priv PrivateKey) Equal(x crypto.PrivateKey) bool
Equal reports whether priv and x have the same value.
func (priv PrivateKey) Public() crypto.PublicKey
Public returns the PublicKey corresponding to priv.
func (priv PrivateKey) Seed() []byte
Seed returns the private key seed corresponding to priv. It is provided for
interoperability with RFC 8032. RFC 8032's private keys correspond to seeds
in this package.
func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error)
Sign signs the given message with priv. rand is ignored and can be nil.
If opts.HashFunc() is crypto.SHA512, the pre-hashed variant Ed25519ph is
used and message is expected to be a SHA-512 hash, otherwise opts.HashFunc()
must be crypto.Hash(0) and the message must not be hashed, as Ed25519
performs two passes over messages to be signed.
A value of type Options can be used as opts, or crypto.Hash(0) or
crypto.SHA512 directly to select plain Ed25519 or Ed25519ph, respectively.
type PublicKey []byte
PublicKey is the type of Ed25519 public keys.
func (pub PublicKey) Equal(x crypto.PublicKey) bool
Equal reports whether pub and x have the same value.
crypto/elliptic
func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error)
GenerateKey returns a public/private key pair. The private key is generated
using the given reader, which must return random data.
Deprecated: for ECDH, use the GenerateKey methods of the crypto/ecdh
package; for ECDSA, use the GenerateKey function of the crypto/ecdsa
package.
func Marshal(curve Curve, x, y *big.Int) []byte
Marshal converts a point on the curve into the uncompressed form specified
in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the curve (or
is the conventional point at infinity), the behavior is undefined.
Deprecated: for ECDH, use the crypto/ecdh package. This function returns an
encoding equivalent to that of PublicKey.Bytes in crypto/ecdh.
func MarshalCompressed(curve Curve, x, y *big.Int) []byte
MarshalCompressed converts a point on the curve into the compressed form
specified in SEC 1, Version 2.0, Section 2.3.3. If the point is not on the
curve (or is the conventional point at infinity), the behavior is undefined.
func Unmarshal(curve Curve, data []byte) (x, y *big.Int)
Unmarshal converts a point, serialized by Marshal, into an x, y pair. It
is an error if the point is not in uncompressed form, is not on the curve,
or is the point at infinity. On error, x = nil.
Deprecated: for ECDH, use the crypto/ecdh package. This function accepts an
encoding equivalent to that of the NewPublicKey methods in crypto/ecdh.
func UnmarshalCompressed(curve Curve, data []byte) (x, y *big.Int)
UnmarshalCompressed converts a point, serialized by MarshalCompressed,
into an x, y pair. It is an error if the point is not in compressed form,
is not on the curve, or is the point at infinity. On error, x = nil.
func bigFromDecimal(s string) *big.Int
func bigFromHex(s string) *big.Int
func initAll()
func initP224()
func initP256()
func initP384()
func initP521()
func panicIfNotOnCurve(curve Curve, x, y *big.Int)
func zForAffine(x, y *big.Int) *big.Int
zForAffine returns a Jacobian Z value for the affine point (x, y). If x and
y are zero, it assumes that they represent the point at infinity because (0,
0) is not on the any of the curves handled here.
TYPES
type Curve interface {
Params() *CurveParams
IsOnCurve(x, y *big.Int) bool
Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int)
Double(x1, y1 *big.Int) (x, y *big.Int)
ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int)
ScalarBaseMult(k []byte) (x, y *big.Int)
}
A Curve represents a short-form Weierstrass curve with a=-3.
The behavior of Add, Double, and ScalarMult when the input is not a point on
the curve is undefined.
Note that the conventional point at infinity (0, 0) is not considered
on the curve, although it can be returned by Add, Double, ScalarMult,
or ScalarBaseMult (but not the Unmarshal or UnmarshalCompressed functions).
Using Curve implementations besides those returned by P224, P256, P384,
and P521 is deprecated.
func P224() Curve
P224 returns a Curve which implements NIST P-224 (FIPS 186-3, section
D.2.2), also known as secp224r1. The CurveParams.Name of this Curve is
"P-224".
Multiple invocations of this function will return the same value, so it can
be used for equality checks and switch statements.
The cryptographic operations are implemented using constant-time algorithms.
func P256() Curve
P256 returns a Curve which implements NIST P-256 (FIPS 186-3, section
D.2.3), also known as secp256r1 or prime256v1. The CurveParams.Name of this
Curve is "P-256".
Multiple invocations of this function will return the same value, so it can
be used for equality checks and switch statements.
The cryptographic operations are implemented using constant-time algorithms.
func P384() Curve
P384 returns a Curve which implements NIST P-384 (FIPS 186-3, section
D.2.4), also known as secp384r1. The CurveParams.Name of this Curve is
"P-384".
Multiple invocations of this function will return the same value, so it can
be used for equality checks and switch statements.
The cryptographic operations are implemented using constant-time algorithms.
func P521() Curve
P521 returns a Curve which implements NIST P-521 (FIPS 186-3, section
D.2.5), also known as secp521r1. The CurveParams.Name of this Curve is
"P-521".
Multiple invocations of this function will return the same value, so it can
be used for equality checks and switch statements.
The cryptographic operations are implemented using constant-time algorithms.
func matchesSpecificCurve(params *CurveParams) (Curve, bool)
type CurveParams struct {
}
CurveParams contains the parameters of an elliptic curve and also provides a
generic, non-constant time implementation of Curve.
The generic Curve implementation is deprecated, and using custom curves
(those not returned by P224, P256, P384, and P521) is not guaranteed to
provide any security property.
func (curve *CurveParams) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)
Add implements [Curve.Add].
Deprecated: the CurveParams methods are deprecated and are not guaranteed
to provide any security property. For ECDH, use the crypto/ecdh package.
For ECDSA, use the crypto/ecdsa package with a Curve value returned directly
from P224, P256, P384, or P521.
func (curve *CurveParams) Double(x1, y1 *big.Int) (*big.Int, *big.Int)
Double implements [Curve.Double].
Deprecated: the CurveParams methods are deprecated and are not guaranteed
to provide any security property. For ECDH, use the crypto/ecdh package.
For ECDSA, use the crypto/ecdsa package with a Curve value returned directly
from P224, P256, P384, or P521.
func (curve *CurveParams) IsOnCurve(x, y *big.Int) bool
IsOnCurve implements [Curve.IsOnCurve].
Deprecated: the CurveParams methods are deprecated and are not guaranteed
to provide any security property. For ECDH, use the crypto/ecdh package.
For ECDSA, use the crypto/ecdsa package with a Curve value returned directly
from P224, P256, P384, or P521.
func (curve *CurveParams) Params() *CurveParams
func (curve *CurveParams) ScalarBaseMult(k []byte) (*big.Int, *big.Int)
ScalarBaseMult implements [Curve.ScalarBaseMult].
Deprecated: the CurveParams methods are deprecated and are not guaranteed
to provide any security property. For ECDH, use the crypto/ecdh package.
For ECDSA, use the crypto/ecdsa package with a Curve value returned directly
from P224, P256, P384, or P521.
func (curve *CurveParams) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int)
ScalarMult implements [Curve.ScalarMult].
Deprecated: the CurveParams methods are deprecated and are not guaranteed
to provide any security property. For ECDH, use the crypto/ecdh package.
For ECDSA, use the crypto/ecdsa package with a Curve value returned directly
from P224, P256, P384, or P521.
func (curve *CurveParams) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int)
addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and (x2,
y2, z2) and returns their sum, also in Jacobian form.
func (curve *CurveParams) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int)
affineFromJacobian reverses the Jacobian transform. See the comment at the
top of the file. If the point is ∞ it returns 0, 0.
func (curve *CurveParams) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int)
doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and returns
its double, also in Jacobian form.
func (curve *CurveParams) polynomial(x *big.Int) *big.Int
polynomial returns x³ - 3x + b.
type nistCurve[Point nistPoint[Point]] struct {
newPoint func() Point
params *CurveParams
}
nistCurve is a Curve implementation based on a nistec Point.
It's a wrapper that exposes the big.Int-based Curve interface and encodes
the legacy idiosyncrasies it requires, such as invalid and infinity point
handling.
To interact with the nistec package, points are encoded into and decoded
from properly formatted byte slices. All big.Int use is limited to this
package. Encoding and decoding is 1/1000th of the runtime of a scalar
multiplication, so the overhead is acceptable.
func (curve *nistCurve[Point]) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)
func (curve *nistCurve[Point]) CombinedMult(Px, Py *big.Int, s1, s2 []byte) (x, y *big.Int)
CombinedMult returns [s1]G + [s2]P where G is the generator. It's used
through an interface upgrade in crypto/ecdsa.
func (curve *nistCurve[Point]) Double(x1, y1 *big.Int) (*big.Int, *big.Int)
func (curve *nistCurve[Point]) IsOnCurve(x, y *big.Int) bool
func (curve *nistCurve[Point]) Params() *CurveParams
func (curve *nistCurve[Point]) ScalarBaseMult(scalar []byte) (*big.Int, *big.Int)
func (curve *nistCurve[Point]) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, *big.Int)
func (curve *nistCurve[Point]) Unmarshal(data []byte) (x, y *big.Int)
func (curve *nistCurve[Point]) UnmarshalCompressed(data []byte) (x, y *big.Int)
func (curve *nistCurve[Point]) normalizeScalar(scalar []byte) []byte
normalizeScalar brings the scalar within the byte size of the order of the
curve, as expected by the nistec scalar multiplication functions.
func (curve *nistCurve[Point]) pointFromAffine(x, y *big.Int) (p Point, err error)
func (curve *nistCurve[Point]) pointToAffine(p Point) (x, y *big.Int)
type nistPoint[T any] interface {
Bytes() []byte
SetBytes([]byte) (T, error)
Add(T, T) T
Double(T) T
ScalarMult(T, []byte) (T, error)
ScalarBaseMult([]byte) (T, error)
}
nistPoint is a generic constraint for the nistec Point types.
type p256Curve struct {
nistCurve[*nistec.P256Point]
}
func (curve *p256Curve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)
func (curve *p256Curve) CombinedMult(Px, Py *big.Int, s1, s2 []byte) (x, y *big.Int)
CombinedMult returns [s1]G + [s2]P where G is the generator. It's used
through an interface upgrade in crypto/ecdsa.
func (curve *p256Curve) Double(x1, y1 *big.Int) (*big.Int, *big.Int)
func (c p256Curve) Inverse(k *big.Int) *big.Int
func (curve *p256Curve) IsOnCurve(x, y *big.Int) bool
func (curve *p256Curve) Params() *CurveParams
func (curve *p256Curve) ScalarBaseMult(scalar []byte) (*big.Int, *big.Int)
func (curve *p256Curve) ScalarMult(Bx, By *big.Int, scalar []byte) (*big.Int, *big.Int)
func (curve *p256Curve) Unmarshal(data []byte) (x, y *big.Int)
func (curve *p256Curve) UnmarshalCompressed(data []byte) (x, y *big.Int)
func (curve *p256Curve) normalizeScalar(scalar []byte) []byte
normalizeScalar brings the scalar within the byte size of the order of the
curve, as expected by the nistec scalar multiplication functions.
func (curve *p256Curve) pointFromAffine(x, y *big.Int) (p Point, err error)
func (curve *p256Curve) pointToAffine(p Point) (x, y *big.Int)
type unmarshaler interface {
Unmarshal([]byte) (x, y *big.Int)
UnmarshalCompressed([]byte) (x, y *big.Int)
}
unmarshaler is implemented by curves with their own constant-time Unmarshal.
There isn't an equivalent interface for Marshal/MarshalCompressed because
that doesn't involve any mathematical operations, only FillBytes and Bit.
crypto/fips140
func Enabled() bool
Enabled reports whether the cryptography libraries are operating in FIPS
140-3 mode.
It can be controlled at runtime using the GODEBUG setting "fips140".
If set to "on", FIPS 140-3 mode is enabled. If set to "only", non-approved
cryptography functions will additionally return errors or panic.
This can't be changed after the program has started.
crypto/hkdf
func Expand[H hash.Hash](h func() H, pseudorandomKey []byte, info string, keyLength int) ([]byte, error)
Expand derives a key from the given hash, key, and optional context info,
returning a []byte of length keyLength that can be used as cryptographic
key. The extraction step is skipped.
The key should have been generated by Extract, or be a uniformly random
or pseudorandom cryptographically strong key. See RFC 5869, Section 3.3.
Most common scenarios will want to use Key instead.
func Extract[H hash.Hash](h func() H, secret, salt []byte) ([]byte, error)
Extract generates a pseudorandom key for use with Expand from an input
secret and an optional independent salt.
Only use this function if you need to reuse the extracted key with multiple
Expand invocations and different context values. Most common scenarios,
including the generation of multiple keys, should use Key instead.
func Key[Hash hash.Hash](h func() Hash, secret, salt []byte, info string, keyLength int) ([]byte, error)
Key derives a key from the given hash, secret, salt and context info,
returning a []byte of length keyLength that can be used as cryptographic
key. Salt and info can be nil.
func checkFIPS140Only[H hash.Hash](h func() H, key []byte) error
crypto/hmac
func Equal(mac1, mac2 []byte) bool
Equal compares two MACs for equality without leaking timing information.
func New(h func() hash.Hash, key []byte) hash.Hash
New returns a new HMAC hash using the given hash.Hash type and key.
New functions like crypto/sha256.New can be used as h. h must return a new
Hash every time it is called. Note that unlike other hash implementations
in the standard library, the returned Hash does not implement
encoding.BinaryMarshaler or encoding.BinaryUnmarshaler.
crypto/internal/boring
func DecryptRSANoPadding(priv *PrivateKeyRSA, ciphertext []byte) ([]byte, error)
func DecryptRSAOAEP(h, mgfHash hash.Hash, priv *PrivateKeyRSA, ciphertext, label []byte) ([]byte, error)
func DecryptRSAPKCS1(priv *PrivateKeyRSA, ciphertext []byte) ([]byte, error)
func ECDH(priv *PrivateKeyECDH, pub *PublicKeyECDH) ([]byte, error)
func EncryptRSANoPadding(pub *PublicKeyRSA, msg []byte) ([]byte, error)
func EncryptRSAOAEP(h, mgfHash hash.Hash, pub *PublicKeyRSA, msg, label []byte) ([]byte, error)
func EncryptRSAPKCS1(pub *PublicKeyRSA, msg []byte) ([]byte, error)
func GenerateKeyECDH(curve string) (*PrivateKeyECDH, []byte, error)
func NewAESCipher(key []byte) (cipher.Block, error)
func NewGCMTLS(c cipher.Block) (cipher.AEAD, error)
func NewGCMTLS13(c cipher.Block) (cipher.AEAD, error)
func NewHMAC(h func() hash.Hash, key []byte) hash.Hash
NewHMAC returns a new HMAC using BoringCrypto. The function h must return a
hash implemented by BoringCrypto (for example, h could be boring.NewSHA256).
If h is not recognized, NewHMAC returns nil.
func NewSHA1() hash.Hash
NewSHA1 returns a new SHA1 hash.
func NewSHA224() hash.Hash
NewSHA224 returns a new SHA224 hash.
func NewSHA256() hash.Hash
NewSHA256 returns a new SHA256 hash.
func NewSHA384() hash.Hash
NewSHA384 returns a new SHA384 hash.
func NewSHA512() hash.Hash
NewSHA512 returns a new SHA512 hash.
func SHA1(p []byte) (sum [20]byte)
func SHA224(p []byte) (sum [28]byte)
func SHA256(p []byte) (sum [32]byte)
func SHA384(p []byte) (sum [48]byte)
func SHA512(p []byte) (sum [64]byte)
func SignMarshalECDSA(priv *PrivateKeyECDSA, hash []byte) ([]byte, error)
func SignRSAPKCS1v15(priv *PrivateKeyRSA, h crypto.Hash, hashed []byte) ([]byte, error)
func SignRSAPSS(priv *PrivateKeyRSA, h crypto.Hash, hashed []byte, saltLen int) ([]byte, error)
func Unreachable()
Unreachable marks code that should be unreachable when BoringCrypto is in
use. It panics.
func UnreachableExceptTests()
UnreachableExceptTests marks code that should be unreachable when
BoringCrypto is in use. It panics.
func VerifyECDSA(pub *PublicKeyECDSA, hash []byte, sig []byte) bool
func VerifyRSAPKCS1v15(pub *PublicKeyRSA, h crypto.Hash, hashed, sig []byte) error
func VerifyRSAPSS(pub *PublicKeyRSA, h crypto.Hash, hashed, sig []byte, saltLen int) error
func addr(p []byte) *byte
addr converts p to its base addr, including a noescape along the way.
If p is nil, addr returns a non-nil pointer, so that the result can always
be dereferenced.
func anyOverlap(x, y []byte) bool
func base(b []byte) *C.uint8_t
base returns the address of the underlying array in b, being careful not to
panic when b has zero length.
func bigBytesECDH(curve string, big *C.GO_BIGNUM) ([]byte, error)
func bigToBN(x BigInt) *C.GO_BIGNUM
func bigToBn(bnp **C.GO_BIGNUM, b BigInt) bool
func bytesToBN(x []byte) *C.GO_BIGNUM
func consumeUint32(b []byte) ([]byte, uint32)
func consumeUint64(b []byte) ([]byte, uint64)
func cryptRSA(withKey func(func(*C.GO_RSA) C.int) C.int,
padding C.int, h, mgfHash hash.Hash, label []byte, saltLen int, ch crypto.Hash,
init func(*C.GO_EVP_PKEY_CTX) C.int,
crypt func(*C.GO_EVP_PKEY_CTX, *C.uint8_t, *C.size_t, *C.uint8_t, C.size_t) C.int,
in []byte) ([]byte, error)
func cryptoHashToMD(ch crypto.Hash) *C.GO_EVP_MD
cryptoHashToMD converts a crypto.Hash to a BoringCrypto *C.GO_EVP_MD.
func curveNID(curve string) (C.int, error)
func curveSize(curve string) int
func decrypt(ctx *C.GO_EVP_PKEY_CTX, out *C.uint8_t, outLen *C.size_t, in *C.uint8_t, inLen C.size_t) C.int
func decryptInit(ctx *C.GO_EVP_PKEY_CTX) C.int
func encrypt(ctx *C.GO_EVP_PKEY_CTX, out *C.uint8_t, outLen *C.size_t, in *C.uint8_t, inLen C.size_t) C.int
func encryptInit(ctx *C.GO_EVP_PKEY_CTX) C.int
func hashToMD(h hash.Hash) *C.GO_EVP_MD
hashToMD converts a hash.Hash implementation from this package to a
BoringCrypto *C.GO_EVP_MD.
func inexactOverlap(x, y []byte) bool
func init()
func newECKey(curve string, X, Y BigInt) (*C.GO_EC_KEY, error)
func noescape(p unsafe.Pointer) unsafe.Pointer
noescape hides a pointer from escape analysis. noescape is the identity
function but escape analysis doesn't think the output depends on the input.
noescape is inlined and currently compiles down to zero instructions.
USE CAREFULLY!
func pointBytesECDH(curve string, group *C.GO_EC_GROUP, pt *C.GO_EC_POINT) ([]byte, error)
func runtime_arg0() string
provided by runtime to avoid os import.
func setupRSA(withKey func(func(*C.GO_RSA) C.int) C.int,
padding C.int, h, mgfHash hash.Hash, label []byte, saltLen int, ch crypto.Hash,
init func(*C.GO_EVP_PKEY_CTX) C.int) (pkey *C.GO_EVP_PKEY, ctx *C.GO_EVP_PKEY_CTX, err error)
func wbase(b BigInt) *C.uint8_t
func xCoordBytesECDH(curve string, group *C.GO_EC_GROUP, pt *C.GO_EC_POINT) ([]byte, error)
TYPES
type BigInt []uint
A BigInt is the raw words from a BigInt. This definition allows us to
avoid importing math/big. Conversion between BigInt and *big.Int is in
crypto/internal/boring/bbig.
func GenerateKeyECDSA(curve string) (X, Y, D BigInt, err error)
func GenerateKeyRSA(bits int) (N, E, D, P, Q, Dp, Dq, Qinv BigInt, err error)
func bnToBig(bn *C.GO_BIGNUM) BigInt
type PrivateKeyECDH struct {
curve string
key *C.GO_EC_KEY
}
func NewPrivateKeyECDH(curve string, bytes []byte) (*PrivateKeyECDH, error)
func (k *PrivateKeyECDH) PublicKey() (*PublicKeyECDH, error)
func (k *PrivateKeyECDH) finalize()
type PrivateKeyECDSA struct {
key *C.GO_EC_KEY
}
func NewPrivateKeyECDSA(curve string, X, Y BigInt, D BigInt) (*PrivateKeyECDSA, error)
func (k *PrivateKeyECDSA) finalize()
type PrivateKeyRSA struct {
_key *C.GO_RSA
}
func NewPrivateKeyRSA(N, E, D, P, Q, Dp, Dq, Qinv BigInt) (*PrivateKeyRSA, error)
func (k *PrivateKeyRSA) finalize()
func (k *PrivateKeyRSA) withKey(f func(*C.GO_RSA) C.int) C.int
type PublicKeyECDH struct {
curve string
key *C.GO_EC_POINT
group *C.GO_EC_GROUP
bytes []byte
}
func NewPublicKeyECDH(curve string, bytes []byte) (*PublicKeyECDH, error)
func (k *PublicKeyECDH) Bytes() []byte
func (k *PublicKeyECDH) finalize()
type PublicKeyECDSA struct {
key *C.GO_EC_KEY
}
func NewPublicKeyECDSA(curve string, X, Y BigInt) (*PublicKeyECDSA, error)
func (k *PublicKeyECDSA) finalize()
type PublicKeyRSA struct {
_key *C.GO_RSA
}
func NewPublicKeyRSA(N, E BigInt) (*PublicKeyRSA, error)
func (k *PublicKeyRSA) finalize()
func (k *PublicKeyRSA) withKey(f func(*C.GO_RSA) C.int) C.int
type aesCBC struct {
key *C.GO_AES_KEY
mode C.int
iv [aesBlockSize]byte
}
func (x *aesCBC) BlockSize() int
func (x *aesCBC) CryptBlocks(dst, src []byte)
func (x *aesCBC) SetIV(iv []byte)
type aesCTR struct {
key *C.GO_AES_KEY
iv [aesBlockSize]byte
num C.uint
ecount_buf [16]C.uint8_t
}
func (x *aesCTR) XORKeyStream(dst, src []byte)
type aesCipher struct {
key []byte
enc C.GO_AES_KEY
dec C.GO_AES_KEY
}
func (c *aesCipher) BlockSize() int
func (c *aesCipher) Decrypt(dst, src []byte)
func (c *aesCipher) Encrypt(dst, src []byte)
func (c *aesCipher) NewCBCDecrypter(iv []byte) cipher.BlockMode
func (c *aesCipher) NewCBCEncrypter(iv []byte) cipher.BlockMode
func (c *aesCipher) NewCTR(iv []byte) cipher.Stream
func (c *aesCipher) NewGCM(nonceSize, tagSize int) (cipher.AEAD, error)
func (c *aesCipher) newGCM(tlsVersion uint16) (cipher.AEAD, error)
type aesGCM struct {
ctx C.GO_EVP_AEAD_CTX
aead *C.GO_EVP_AEAD
}
func (g *aesGCM) NonceSize() int
func (g *aesGCM) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
func (g *aesGCM) Overhead() int
func (g *aesGCM) Seal(dst, nonce, plaintext, additionalData []byte) []byte
func (g *aesGCM) finalize()
type aesKeySizeError int
func (k aesKeySizeError) Error() string
type aesNonceSizeError int
func (n aesNonceSizeError) Error() string
type boringHMAC struct {
md *C.GO_EVP_MD
ctx C.GO_HMAC_CTX
ctx2 C.GO_HMAC_CTX
size int
blockSize int
key []byte
sum []byte
needCleanup bool
}
func (h *boringHMAC) BlockSize() int
func (h *boringHMAC) Reset()
func (h *boringHMAC) Size() int
func (h *boringHMAC) Sum(in []byte) []byte
func (h *boringHMAC) Write(p []byte) (int, error)
func (h *boringHMAC) finalize()
type ecdsaSignature struct {
R, S BigInt
}
type extraModes interface {
NewCBCEncrypter(iv []byte) cipher.BlockMode
NewCBCDecrypter(iv []byte) cipher.BlockMode
NewCTR(iv []byte) cipher.Stream
NewGCM(nonceSize, tagSize int) (cipher.AEAD, error)
}
var _ extraModes = (*aesCipher)(nil)
type fail string
func (e fail) Error() string
type noGCM struct {
cipher.Block
}
type randReader int
func (randReader) Read(b []byte) (int, error)
type sha1Ctx struct {
h [5]uint32
nl, nh uint32
x [64]byte
nx uint32
}
type sha1Hash struct {
ctx C.GO_SHA_CTX
out [20]byte
}
func (h *sha1Hash) AppendBinary(b []byte) ([]byte, error)
func (h *sha1Hash) BlockSize() int
func (h *sha1Hash) MarshalBinary() ([]byte, error)
func (h *sha1Hash) Reset()
func (h *sha1Hash) Size() int
func (h *sha1Hash) Sum(dst []byte) []byte
func (h *sha1Hash) UnmarshalBinary(b []byte) error
func (h *sha1Hash) Write(p []byte) (int, error)
func (h *sha1Hash) noescapeCtx() *C.GO_SHA_CTX
func (h0 *sha1Hash) sum(dst []byte) []byte
type sha224Hash struct {
ctx C.GO_SHA256_CTX
out [224 / 8]byte
}
func (h *sha224Hash) AppendBinary(b []byte) ([]byte, error)
func (h *sha224Hash) BlockSize() int
func (h *sha224Hash) MarshalBinary() ([]byte, error)
func (h *sha224Hash) Reset()
func (h *sha224Hash) Size() int
func (h *sha224Hash) Sum(dst []byte) []byte
func (h *sha224Hash) UnmarshalBinary(b []byte) error
func (h *sha224Hash) Write(p []byte) (int, error)
func (h *sha224Hash) noescapeCtx() *C.GO_SHA256_CTX
func (h0 *sha224Hash) sum(dst []byte) []byte
type sha256Ctx struct {
h [8]uint32
nl, nh uint32
x [64]byte
nx uint32
}
type sha256Hash struct {
ctx C.GO_SHA256_CTX
out [256 / 8]byte
}
func (h *sha256Hash) AppendBinary(b []byte) ([]byte, error)
func (h *sha256Hash) BlockSize() int
func (h *sha256Hash) MarshalBinary() ([]byte, error)
func (h *sha256Hash) Reset()
func (h *sha256Hash) Size() int
func (h *sha256Hash) Sum(dst []byte) []byte
func (h *sha256Hash) UnmarshalBinary(b []byte) error
func (h *sha256Hash) Write(p []byte) (int, error)
func (h *sha256Hash) noescapeCtx() *C.GO_SHA256_CTX
func (h0 *sha256Hash) sum(dst []byte) []byte
type sha384Hash struct {
ctx C.GO_SHA512_CTX
out [384 / 8]byte
}
func (h *sha384Hash) AppendBinary(b []byte) ([]byte, error)
func (h *sha384Hash) BlockSize() int
func (h *sha384Hash) MarshalBinary() ([]byte, error)
func (h *sha384Hash) Reset()
func (h *sha384Hash) Size() int
func (h *sha384Hash) Sum(dst []byte) []byte
func (h *sha384Hash) UnmarshalBinary(b []byte) error
func (h *sha384Hash) Write(p []byte) (int, error)
func (h *sha384Hash) noescapeCtx() *C.GO_SHA512_CTX
func (h0 *sha384Hash) sum(dst []byte) []byte
type sha512Ctx struct {
h [8]uint64
nl, nh uint64
x [128]byte
nx uint32
}
type sha512Hash struct {
ctx C.GO_SHA512_CTX
out [512 / 8]byte
}
func (h *sha512Hash) AppendBinary(b []byte) ([]byte, error)
func (h *sha512Hash) BlockSize() int
func (h *sha512Hash) MarshalBinary() ([]byte, error)
func (h *sha512Hash) Reset()
func (h *sha512Hash) Size() int
func (h *sha512Hash) Sum(dst []byte) []byte
func (h *sha512Hash) UnmarshalBinary(b []byte) error
func (h *sha512Hash) Write(p []byte) (int, error)
func (h *sha512Hash) noescapeCtx() *C.GO_SHA512_CTX
func (h0 *sha512Hash) sum(dst []byte) []byte
crypto/internal/boring/bbig
func Dec(b boring.BigInt) *big.Int
func Enc(b *big.Int) boring.BigInt
crypto/internal/boring/bcache
func registerCache(unsafe.Pointer)
TYPES
type Cache[K, V any] struct {
ptable atomic.Pointer[cacheTable[K, V]]
}
A Cache is a GC-friendly concurrent map from unsafe.Pointer to
unsafe.Pointer. It is meant to be used for maintaining shadow BoringCrypto
state associated with certain allocated structs, in particular public and
private RSA and ECDSA keys.
The cache is GC-friendly in the sense that the keys do not indefinitely
prevent the garbage collector from collecting them. Instead, at the start
of each GC, the cache is cleared entirely. That is, the cache is lossy,
and the loss happens at the start of each GC. This means that clients need
to be able to cope with cache entries disappearing, but it also means that
clients don't need to worry about cache entries keeping the keys from being
collected.
func (c *Cache[K, V]) Clear()
Clear clears the cache. The runtime does this automatically at each garbage
collection; this method is exposed only for testing.
func (c *Cache[K, V]) Get(k *K) *V
Get returns the cached value associated with v, which is either the value
v corresponding to the most recent call to Put(k, v) or nil if that cache
entry has been dropped.
func (c *Cache[K, V]) Put(k *K, v *V)
Put sets the cached value associated with k to v.
func (c *Cache[K, V]) Register()
Register registers the cache with the runtime, so that c.ptable can be
cleared at the start of each GC. Register must be called during package
initialization.
func (c *Cache[K, V]) table() *cacheTable[K, V]
table returns a pointer to the current cache hash table, coping with the
possibility of the GC clearing it out from under us.
type cacheEntry[K, V any] struct {
}
A cacheEntry is a single entry in the linked list for a given hash table
entry.
type cacheTable[K, V any] [cacheSize]atomic.Pointer[cacheEntry[K, V]]
crypto/internal/boring/sig
func BoringCrypto()
BoringCrypto indicates that the BoringCrypto module is present.
func FIPSOnly()
FIPSOnly indicates that package crypto/tls/fipsonly is present.
func StandardCrypto()
StandardCrypto indicates that standard Go crypto is present.
crypto/internal/boring/syso
crypto/internal/cryptotest
func FetchModule(t *testing.T, module, version string) string
FetchModule fetches the module at the given version and returns the
directory containing its source tree. It skips the test if fetching modules
is not possible in this environment.
func SkipTestAllocations(t *testing.T)
SkipTestAllocations skips the test if there are any factors that interfere
with allocation optimizations.
func TestAEAD(t *testing.T, mAEAD MakeAEAD)
TestAEAD performs a set of tests on cipher.AEAD implementations, checking
the documented requirements of NonceSize, Overhead, Seal and Open.
func TestAllImplementations(t *testing.T, pkg string, f func(t *testing.T))
TestAllImplementations runs the provided test function with each available
implementation of the package registered with crypto/internal/impl. If there
are no alternative implementations for pkg, f is invoked directly once.
func TestBlock(t *testing.T, keySize int, mb MakeBlock)
TestBlock performs a set of tests on cipher.Block implementations, checking
the documented requirements of BlockSize, Encrypt, and Decrypt.
func TestBlockMode(t *testing.T, block cipher.Block, makeEncrypter, makeDecrypter MakeBlockMode)
TestBlockMode performs a set of tests on cipher.BlockMode implementations,
checking the documented requirements of CryptBlocks.
func TestHash(t *testing.T, mh MakeHash)
TestHash performs a set of tests on hash.Hash implementations, checking the
documented requirements of Write, Sum, Reset, Size, and BlockSize.
func TestStream(t *testing.T, ms MakeStream)
TestStream performs a set of tests on cipher.Stream implementations,
checking the documented requirements of XORKeyStream.
func TestStreamFromBlock(t *testing.T, block cipher.Block, blockMode func(b cipher.Block, iv []byte) cipher.Stream)
TestStreamFromBlock creates a Stream from a cipher.Block used in a
cipher.BlockMode. It addresses Issue 68377 by checking for a panic when the
BlockMode uses an IV with incorrect length. For a valid IV, it also runs all
TestStream tests on the resulting stream.
func getSum(t *testing.T, h hash.Hash, buff []byte) []byte
Helper function for getting Sum. Checks that Sum doesn't change hash state.
func isDeterministic(aead cipher.AEAD) bool
func mustPanic(t *testing.T, msg string, f func())
func newRandReader(t *testing.T) io.Reader
func openWithoutError(t *testing.T, aead cipher.AEAD, plaintext, nonce, ciphertext, addData []byte) []byte
Helper function to Open and authenticate ciphertext. Checks that Open
doesn't error (assuming ciphertext was well-formed with corresponding nonce
and additional data).
func sealMsg(t *testing.T, aead cipher.AEAD, ciphertext, nonce, plaintext, addData []byte) []byte
Helper function to Seal a plaintext with additional data. Checks that
ciphertext isn't bigger than the plaintext length plus Overhead()
func testBlockMode(t *testing.T, bm MakeBlockMode, b cipher.Block, iv []byte)
func testBlockModePair(t *testing.T, b cipher.Block, enc, dec MakeBlockMode, iv []byte)
func testCipher(t *testing.T, cipher func(dst, src []byte), blockSize int)
func truncateHex(b []byte) string
func writeToHash(t *testing.T, h hash.Hash, p []byte)
Helper function for writing. Verifies that Write does not error.
TYPES
type MakeAEAD func() (cipher.AEAD, error)
MakeAEAD returns a cipher.AEAD instance.
Multiple calls to MakeAEAD must return equivalent instances, so for example
the key must be fixed.
type MakeBlock func(key []byte) (cipher.Block, error)
type MakeBlockMode func(b cipher.Block, iv []byte) cipher.BlockMode
MakeBlockMode returns a cipher.BlockMode instance. It expects len(iv) ==
b.BlockSize().
type MakeHash func() hash.Hash
type MakeStream func() cipher.Stream
MakeStream returns a cipher.Stream instance.
Multiple calls to MakeStream must return equivalent instances, so for
example the key and/or IV must be fixed.
crypto/internal/entropy
func Depleted(LOAD func(*[48]byte))
Depleted notifies the entropy source that the entropy in the module is
"depleted" and provides the callback for the LOAD command.
crypto/internal/fips140
func CAST(name string, f func() error)
CAST runs the named Cryptographic Algorithm Self-Test (if operated in FIPS
mode) and aborts the program (stopping the module input/output and entering
the "error state") if the self-test fails.
CASTs are mandatory self-checks that must be performed by FIPS 140-3 modules
before the algorithm is used. See Implementation Guidance 10.3.A.
The name must not contain commas, colons, hashes, or equal signs.
If a package p calls CAST from its init function, an import of p should also
be added to crypto/internal/fips140test. If a package p calls CAST on the
first use of the algorithm, an invocation of that algorithm should be added
to fipstest.TestConditionals.
func PCT(name string, f func() error) error
PCT runs the named Pairwise Consistency Test (if operated in FIPS mode) and
returns any errors. If an error is returned, the key must not be used.
PCTs are mandatory for every key pair that is generated/imported, including
ephemeral keys (which effectively doubles the cost of key establishment).
See Implementation Guidance 10.3.A Additional Comment 1.
The name must not contain commas, colons, hashes, or equal signs.
If a package p calls PCT during key generation, an invocation of that
function should be added to fipstest.TestConditionals.
func RecordApproved()
RecordApproved is an internal function that records the use of an approved
service. It does not override RecordNonApproved calls in the same span.
It should be called by exposed functions that perform a whole cryptographic
alrgorithm (e.g. by Sum, not by New, unless a cryptographic Instantiate
algorithm is performed) and should be called after any checks that may cause
the function to error out or panic.
func RecordNonApproved()
RecordNonApproved is an internal function that records the use of a
non-approved service. It overrides any RecordApproved calls in the same
span.
func ResetServiceIndicator()
ResetServiceIndicator clears the service indicator for the running
goroutine.
func ServiceIndicator() bool
ServiceIndicator returns true if and only if all services invoked by this
goroutine since the last ResetServiceIndicator call are approved.
If ResetServiceIndicator was not called before by this goroutine, its return
value is undefined.
func fatal(string)
fatal is [runtime.fatal], pushed via linkname.
func getIndicator() uint8
func init()
func setIndicator(uint8)
TYPES
type Hash interface {
io.Writer
Sum(b []byte) []byte
Reset()
Size() int
BlockSize() int
}
Hash is the common interface implemented by all hash functions. It is a
copy of hash.Hash from the standard library, to avoid depending on security
definitions from outside of the module.
crypto/internal/fips140/aes
func EncryptionKeySchedule(c *Block) []uint32
EncryptionKeySchedule is used from the GCM implementation to access the
precomputed AES key schedule, to pass to the assembly implementation.
func RoundToBlock(c *CTR)
RoundToBlock is used by CTR_DRBG, which discards the rightmost unused bits
at each request. It rounds the offset up to the next block boundary.
func add128(lo, hi uint64, x uint64) (uint64, uint64)
func checkGenericIsExpected()
checkGenericIsExpected is called by the variable-time implementation to make
sure it is not used when hardware support is available. It shouldn't happen,
but this way it's more evidently correct.
func cryptBlocksDec(b *Block, civ *[BlockSize]byte, dst, src []byte)
func cryptBlocksDecGeneric(b *Block, civ *[BlockSize]byte, dst, src []byte)
func cryptBlocksEnc(b *Block, civ *[BlockSize]byte, dst, src []byte)
func cryptBlocksEncGeneric(b *Block, civ *[BlockSize]byte, dst, src []byte)
func ctrBlocks(b *Block, dst, src []byte, ivlo, ivhi uint64)
func ctrBlocks1(b *Block, dst, src *[BlockSize]byte, ivlo, ivhi uint64)
func ctrBlocks1Asm(nr int, xk *[60]uint32, dst, src *[BlockSize]byte, ivlo, ivhi uint64)
func ctrBlocks2(b *Block, dst, src *[2 * BlockSize]byte, ivlo, ivhi uint64)
func ctrBlocks2Asm(nr int, xk *[60]uint32, dst, src *[2 * BlockSize]byte, ivlo, ivhi uint64)
func ctrBlocks4(b *Block, dst, src *[4 * BlockSize]byte, ivlo, ivhi uint64)
func ctrBlocks4Asm(nr int, xk *[60]uint32, dst, src *[4 * BlockSize]byte, ivlo, ivhi uint64)
func ctrBlocks8(b *Block, dst, src *[8 * BlockSize]byte, ivlo, ivhi uint64)
func ctrBlocks8Asm(nr int, xk *[60]uint32, dst, src *[8 * BlockSize]byte, ivlo, ivhi uint64)
func decryptBlock(c *Block, dst, src []byte)
func decryptBlockAsm(nr int, xk *uint32, dst, src *byte)
func decryptBlockGeneric(c *blockExpanded, dst, src []byte)
Decrypt one block from src into dst, using the expanded key xk.
func encryptBlock(c *Block, dst, src []byte)
func encryptBlockAsm(nr int, xk *uint32, dst, src *byte)
func encryptBlockGeneric(c *blockExpanded, dst, src []byte)
Encrypt one block from src into dst, using the expanded key xk.
func expandKeyAsm(nr int, key *byte, enc *uint32, dec *uint32)
func expandKeyGeneric(c *blockExpanded, key []byte)
Key expansion algorithm. See FIPS-197, Figure 11. Their rcon[i] is our
powx[i-1] << 24.
func init()
func newBlockExpanded(c *blockExpanded, key []byte)
func rotw(w uint32) uint32
Rotate
func subw(w uint32) uint32
Apply sbox0 to each byte in w.
TYPES
type Block struct {
block
}
A Block is an instance of AES using a particular key. It is safe for
concurrent use.
func New(key []byte) (*Block, error)
New creates and returns a new [cipher.Block] implementation. The key
argument should be the AES key, either 16, 24, or 32 bytes to select
AES-128, AES-192, or AES-256.
func newBlock(c *Block, key []byte) *Block
func newOutlined(b *Block, key []byte) (*Block, error)
newOutlined is marked go:noinline to avoid it inlining into New, and making
New too complex to inline itself.
func (c *Block) BlockSize() int
func (c *Block) Decrypt(dst, src []byte)
func (c *Block) Encrypt(dst, src []byte)
func (b *Block) roundKeysSize() int
roundKeysSize returns the number of uint32 of c.end or c.dec that are used.
type CBCDecrypter struct {
b Block
iv [BlockSize]byte
}
func NewCBCDecrypter(b *Block, iv [BlockSize]byte) *CBCDecrypter
NewCBCDecrypter returns a [cipher.BlockMode] which decrypts in cipher block
chaining mode, using the given Block.
func (c *CBCDecrypter) BlockSize() int
func (c *CBCDecrypter) CryptBlocks(dst, src []byte)
func (x *CBCDecrypter) SetIV(iv []byte)
type CBCEncrypter struct {
b Block
iv [BlockSize]byte
}
func NewCBCEncrypter(b *Block, iv [BlockSize]byte) *CBCEncrypter
NewCBCEncrypter returns a [cipher.BlockMode] which encrypts in cipher block
chaining mode, using the given Block.
func (c *CBCEncrypter) BlockSize() int
func (c *CBCEncrypter) CryptBlocks(dst, src []byte)
func (x *CBCEncrypter) SetIV(iv []byte)
type CTR struct {
b Block
}
func NewCTR(b *Block, iv []byte) *CTR
func newCTR(b *Block, iv []byte) CTR
func (c *CTR) XORKeyStream(dst, src []byte)
func (c *CTR) XORKeyStreamAt(dst, src []byte, offset uint64)
XORKeyStreamAt behaves like XORKeyStream but keeps no state, and instead
seeks into the keystream by the given bytes offset from the start (ignoring
any XORKetStream calls). This allows for random access into the keystream,
up to 16 EiB from the start.
type KeySizeError int
func (k KeySizeError) Error() string
type block struct {
blockExpanded
}
func (b *block) roundKeysSize() int
roundKeysSize returns the number of uint32 of c.end or c.dec that are used.
type blockExpanded struct {
rounds int
enc [60]uint32
dec [60]uint32
}
blockExpanded is the block type used for all architectures except s390x,
which feeds the raw key directly to its instructions.
func (b *blockExpanded) roundKeysSize() int
roundKeysSize returns the number of uint32 of c.end or c.dec that are used.
crypto/internal/fips140/aes/gcm
func GHASH(key *[16]byte, inputs ...[]byte) []byte
GHASH is exposed to allow crypto/cipher to implement non-AES GCM modes.
It is not allowed as a stand-alone operation in FIPS mode because it is not
ACVP tested.
func SealWithRandomNonce(g *GCM, nonce, out, plaintext, additionalData []byte)
SealWithRandomNonce encrypts plaintext to out, and writes a random
nonce to nonce. nonce must be 12 bytes, and out must be 16 bytes longer
than plaintext. out and plaintext may overlap exactly or not at all.
additionalData and out must not overlap.
This complies with FIPS 140-3 IG C.H Scenario 2.
Note that this is NOT a [cipher.AEAD].Seal method.
func checkGenericIsExpected()
checkGenericIsExpected is called by the variable-time implementation to make
sure it is not used when hardware support is available. It shouldn't happen,
but this way it's more evidently correct.
func deriveCounterGeneric(H, counter *[gcmBlockSize]byte, nonce []byte)
deriveCounterGeneric computes the initial GCM counter state from the given
nonce. See NIST SP 800-38D, section 7.1. This assumes that counter is filled
with zeros on entry.
func gcmAesData(productTable *[256]byte, data []byte, T *[16]byte)
func gcmAesDec(productTable *[256]byte, dst, src []byte, ctr, T *[16]byte, ks []uint32)
func gcmAesEnc(productTable *[256]byte, dst, src []byte, ctr, T *[16]byte, ks []uint32)
func gcmAesFinish(productTable *[256]byte, tagMask, T *[16]byte, pLen, dLen uint64)
func gcmAesInit(productTable *[256]byte, ks []uint32)
func gcmAuthGeneric(out []byte, H, tagMask *[gcmBlockSize]byte, ciphertext, additionalData []byte)
gcmAuthGeneric calculates GHASH(additionalData, ciphertext), masks the
result with tagMask and writes the result to out.
func gcmCounterCryptGeneric(b *aes.Block, out, src []byte, counter *[gcmBlockSize]byte)
gcmCounterCryptGeneric encrypts src using AES in counter mode with 32-bit
wrapping (which is different from AES-CTR) and places the result into out.
counter is the initial value and will be updated with the next value.
func gcmInc32(counterBlock *[gcmBlockSize]byte)
gcmInc32 treats the final four bytes of counterBlock as a big-endian value
and increments it.
func ghash(out, H *[gcmBlockSize]byte, inputs ...[]byte)
ghash is a variable-time generic implementation of GHASH, which shouldn't be
used on any architecture with hardware support for AES-GCM.
Each input is zero-padded to 128-bit before being absorbed.
func ghashMul(productTable *[16]gcmFieldElement, y *gcmFieldElement)
ghashMul sets y to y*H, where H is the GCM key, fixed during New.
func ghashUpdate(productTable *[16]gcmFieldElement, y *gcmFieldElement, data []byte)
ghashUpdate extends y with more polynomial terms from data. If data is not a
multiple of gcmBlockSize bytes long then the remainder is zero padded.
func init()
func initGCM(g *GCM)
func open(out []byte, g *GCM, nonce, ciphertext, data []byte) error
func openGeneric(out []byte, g *GCM, nonce, ciphertext, additionalData []byte) error
func reverseBits(i int) int
reverseBits reverses the order of the bits of 4-bit number in i.
func seal(out []byte, g *GCM, nonce, plaintext, data []byte)
func sealGeneric(out []byte, g *GCM, nonce, plaintext, additionalData []byte)
func shiftLeft(x *[aes.BlockSize]byte) byte
shiftLeft sets x to x << 1, and returns MSB₁(x).
func sliceForAppend(in []byte, n int) (head, tail []byte)
sliceForAppend takes a slice and a requested number of bytes. It returns a
slice with the contents of the given slice followed by that many bytes and a
second slice that aliases into it and contains only the extra bytes. If the
original slice has sufficient capacity then no allocation is performed.
func updateBlocks(productTable *[16]gcmFieldElement, y *gcmFieldElement, blocks []byte)
updateBlocks extends y with more polynomial terms from blocks, based on
Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks.
TYPES
type CMAC struct {
b aes.Block
k1 [aes.BlockSize]byte
k2 [aes.BlockSize]byte
}
CMAC implements the CMAC mode from NIST SP 800-38B.
It is optimized for use in Counter KDF (SP 800-108r1) and XAES-256-GCM
as a stand-alone MAC.
func NewCMAC(b *aes.Block) *CMAC
func (c *CMAC) MAC(m []byte) [aes.BlockSize]byte
func (c *CMAC) deriveSubkeys()
type CounterKDF struct {
mac CMAC
}
CounterKDF implements a KDF in Counter Mode instantiated with CMAC-AES,
according to NIST SP 800-108 Revision 1 Update 1, Section 4.1.
It produces a 256-bit output, and accepts a 8-bit Label and a 96-bit
Context. It uses a counter of 16 bits placed before the fixed data. The
fixed data is the sequence Label || 0x00 || Context. The L field is omitted,
since the output key length is fixed.
rather than for exposing it to applications as a stand-alone KDF.
func NewCounterKDF(b *aes.Block) *CounterKDF
NewCounterKDF creates a new CounterKDF with the given key.
func (kdf *CounterKDF) DeriveKey(label byte, context [12]byte) [32]byte
DeriveKey derives a key from the given label and context.
type GCM struct {
cipher aes.Block
nonceSize int
tagSize int
gcmPlatformData
}
GCM represents a Galois Counter Mode with a specific key.
func New(cipher *aes.Block, nonceSize, tagSize int) (*GCM, error)
func newGCM(g *GCM, cipher *aes.Block, nonceSize, tagSize int) (*GCM, error)
newGCM is marked go:noinline to avoid it inlining into New, and making New
too complex to inline itself.
func (g *GCM) NonceSize() int
func (g *GCM) Open(dst, nonce, ciphertext, data []byte) ([]byte, error)
func (g *GCM) Overhead() int
func (g *GCM) Seal(dst, nonce, plaintext, data []byte) []byte
func (g *GCM) sealAfterIndicator(dst, nonce, plaintext, data []byte) []byte
type GCMForSSH struct {
g GCM
ready bool
start uint64
next uint64
}
func NewGCMForSSH(cipher *aes.Block) (*GCMForSSH, error)
NewGCMForSSH returns a new AEAD that works like GCM, but enforces the
construction of nonces as specified in RFC 5647.
This complies with FIPS 140-3 IG C.H Scenario 1.d.
func (g *GCMForSSH) NonceSize() int
func (g *GCMForSSH) Open(dst, nonce, ciphertext, data []byte) ([]byte, error)
func (g *GCMForSSH) Overhead() int
func (g *GCMForSSH) Seal(dst, nonce, plaintext, data []byte) []byte
type GCMForTLS12 struct {
g GCM
next uint64
}
func NewGCMForTLS12(cipher *aes.Block) (*GCMForTLS12, error)
NewGCMForTLS12 returns a new AEAD that works like GCM, but enforces the
construction of nonces as specified in RFC 5288, Section 3 and RFC 9325,
Section 7.2.1.
This complies with FIPS 140-3 IG C.H Scenario 1.a.
func (g *GCMForTLS12) NonceSize() int
func (g *GCMForTLS12) Open(dst, nonce, ciphertext, data []byte) ([]byte, error)
func (g *GCMForTLS12) Overhead() int
func (g *GCMForTLS12) Seal(dst, nonce, plaintext, data []byte) []byte
type GCMForTLS13 struct {
g GCM
ready bool
mask uint64
next uint64
}
func NewGCMForTLS13(cipher *aes.Block) (*GCMForTLS13, error)
NewGCMForTLS13 returns a new AEAD that works like GCM, but enforces the
construction of nonces as specified in RFC 8446, Section 5.3.
func (g *GCMForTLS13) NonceSize() int
func (g *GCMForTLS13) Open(dst, nonce, ciphertext, data []byte) ([]byte, error)
func (g *GCMForTLS13) Overhead() int
func (g *GCMForTLS13) Seal(dst, nonce, plaintext, data []byte) []byte
type GCMWithCounterNonce struct {
g GCM
ready bool
fixedName uint32
start uint64
next uint64
}
func NewGCMWithCounterNonce(cipher *aes.Block) (*GCMWithCounterNonce, error)
NewGCMWithCounterNonce returns a new AEAD that works like GCM, but enforces
the construction of deterministic nonces. The nonce must be 96 bits,
the first 32 bits must be an encoding of the module name, and the last 64
bits must be a counter.
This complies with FIPS 140-3 IG C.H Scenario 3.
func (g *GCMWithCounterNonce) NonceSize() int
func (g *GCMWithCounterNonce) Open(dst, nonce, ciphertext, data []byte) ([]byte, error)
func (g *GCMWithCounterNonce) Overhead() int
func (g *GCMWithCounterNonce) Seal(dst, nonce, plaintext, data []byte) []byte
type gcmFieldElement struct {
low, high uint64
}
gcmFieldElement represents a value in GF(2¹²⁸). In order to reflect the GCM
standard and make binary.BigEndian suitable for marshaling these values,
the bits are stored in big endian order. For example:
the coefficient of x⁰ can be obtained by v.low >> 63.
the coefficient of x⁶³ can be obtained by v.low & 1.
the coefficient of x⁶⁴ can be obtained by v.high >> 63.
the coefficient of x¹²⁷ can be obtained by v.high & 1.
func ghashAdd(x, y *gcmFieldElement) gcmFieldElement
ghashAdd adds two elements of GF(2¹²⁸) and returns the sum.
func ghashDouble(x *gcmFieldElement) (double gcmFieldElement)
ghashDouble returns the result of doubling an element of GF(2¹²⁸).
type gcmPlatformData struct {
productTable [256]byte
}
crypto/internal/fips140/alias
func AnyOverlap(x, y []byte) bool
AnyOverlap reports whether x and y share memory at any (not necessarily
corresponding) index. The memory beyond the slice length is ignored.
func InexactOverlap(x, y []byte) bool
InexactOverlap reports whether x and y share memory at any non-corresponding
index. The memory beyond the slice length is ignored. Note that x and y can
have different lengths and still not have any inexact overlap.
InexactOverlap can be used to implement the requirements of the
crypto/cipher AEAD, Block, BlockMode and Stream interfaces.
crypto/internal/fips140/bigmod
func addMulVVW(z, x []uint, y uint) (carry uint)
addMulVVW multiplies the multi-word value x by the single-word value y,
adding the result to the multi-word value z and returning the final carry.
It can be thought of as one row of a pen-and-paper column multiplication.
func addMulVVW1024(z, x *uint, y uint) (c uint)
func addMulVVW1536(z, x *uint, y uint) (c uint)
func addMulVVW2048(z, x *uint, y uint) (c uint)
func bigEndianUint(buf []byte) uint
bigEndianUint returns the contents of buf interpreted as a big-endian
encoded uint value.
func bitLen(n uint) int
bitLen is a version of bits.Len that only leaks the bit length of n,
but not its value. bits.Len and bits.LeadingZeros use a lookup table for the
low-order bits on some architectures.
func ctMask(on choice) uint
ctMask is all 1s if on is yes, and all 0s otherwise.
func init()
func minusInverseModW(x uint) uint
minusInverseModW computes -x⁻¹ mod _W with x odd.
This operation is used to precompute a constant involved in Montgomery
multiplication.
func rshift1(a *Nat, carry uint)
TYPES
type Modulus struct {
nat *Nat
odd bool
}
Modulus is used for modular arithmetic, precomputing relevant constants.
A Modulus can leak the exact number of bits needed to store its value and is
stored without padding. Its actual value is still kept secret.
func NewModulus(b []byte) (*Modulus, error)
NewModulus creates a new Modulus from a slice of big-endian bytes. The
modulus must be greater than one.
The number of significant bits and whether the modulus is even is leaked
through timing side-channels.
func NewModulusProduct(a, b []byte) (*Modulus, error)
NewModulusProduct creates a new Modulus from the product of two numbers
represented as big-endian byte slices. The result must be greater than one.
func newModulus(n *Nat) (*Modulus, error)
func (m *Modulus) BitLen() int
BitLen returns the size of m in bits.
func (m *Modulus) Nat() *Nat
Nat returns m as a Nat.
func (m *Modulus) Size() int
Size returns the size of m in bytes.
type Nat struct {
limbs []uint
}
Nat represents an arbitrary natural number
Each Nat has an announced length, which is the number of limbs it has
stored. Operations on this number are allowed to leak this length, but will
not leak any information about the values contained in those limbs.
func NewNat() *Nat
NewNat returns a new nat with a size of zero, just like new(Nat), but with
the preallocated capacity to hold a number of up to preallocTarget bits.
NewNat inlines, so the allocation can live on the stack.
func rr(m *Modulus) *Nat
rr returns R*R with R = 2^(_W * n) and n = len(m.nat.limbs).
func (x *Nat) Add(y *Nat, m *Modulus) *Nat
Add computes x = x + y mod m.
The length of both operands must be the same as the modulus. Both operands
must already be reduced modulo m.
func (x *Nat) BitLenVarTime() int
BitLenVarTime returns the actual size of x in bits.
The actual size of x (but nothing more) leaks through timing side-channels.
Note that this is ordinarily secret, as opposed to the announced size of x.
func (x *Nat) Bytes(m *Modulus) []byte
Bytes returns x as a zero-extended big-endian byte slice. The size of the
slice will match the size of m.
x must have the same size as m and it must be less than or equal to m.
func (x *Nat) Equal(y *Nat) choice
Equal returns 1 if x == y, and 0 otherwise.
Both operands must have the same announced length.
func (out *Nat) Exp(x *Nat, e []byte, m *Modulus) *Nat
Exp calculates out = x^e mod m.
The exponent e is represented in big-endian order. The output will be
resized to the size of m and overwritten. x must already be reduced modulo
m.
m must be odd, or Exp will panic.
func (out *Nat) ExpShortVarTime(x *Nat, e uint, m *Modulus) *Nat
ExpShortVarTime calculates out = x^e mod m.
The output will be resized to the size of m and overwritten. x must already
be reduced modulo m. This leaks the exponent through timing side-channels.
m must be odd, or ExpShortVarTime will panic.
func (x *Nat) ExpandFor(m *Modulus) *Nat
ExpandFor ensures x has the right size to work with operations modulo m.
The announced size of x must be smaller than or equal to that of m.
func (x *Nat) InverseVarTime(a *Nat, m *Modulus) (*Nat, bool)
InverseVarTime calculates x = a⁻¹ mod m and returns (x, true) if a is
invertible. Otherwise, InverseVarTime returns (x, false) and x is not
modified.
a must be reduced modulo m, but doesn't need to have the same size.
The output will be resized to the size of m and overwritten.
func (x *Nat) IsMinusOne(m *Modulus) choice
IsMinusOne returns 1 if x == -1 mod m, and 0 otherwise.
The length of x must be the same as the modulus. x must already be reduced
modulo m.
func (x *Nat) IsOdd() choice
IsOdd returns 1 if x is odd, and 0 otherwise.
func (x *Nat) IsOne() choice
IsOne returns 1 if x == 1, and 0 otherwise.
func (x *Nat) IsZero() choice
IsZero returns 1 if x == 0, and 0 otherwise.
func (out *Nat) Mod(x *Nat, m *Modulus) *Nat
Mod calculates out = x mod m.
This works regardless how large the value of x is.
The output will be resized to the size of m and overwritten.
func (x *Nat) Mul(y *Nat, m *Modulus) *Nat
Mul calculates x = x * y mod m.
The length of both operands must be the same as the modulus. Both operands
must already be reduced modulo m.
func (x *Nat) SetBytes(b []byte, m *Modulus) (*Nat, error)
SetBytes assigns x = b, where b is a slice of big-endian bytes. SetBytes
returns an error if b >= m.
The output will be resized to the size of m and overwritten.
func (x *Nat) SetOverflowingBytes(b []byte, m *Modulus) (*Nat, error)
SetOverflowingBytes assigns x = b, where b is a slice of big-endian bytes.
SetOverflowingBytes returns an error if b has a longer bit length than m,
but reduces overflowing values up to 2^⌈log2(m)⌉ - 1.
The output will be resized to the size of m and overwritten.
func (x *Nat) SetUint(y uint) *Nat
SetUint assigns x = y.
The output will be resized to a single limb and overwritten.
func (x *Nat) ShiftRightVarTime(n uint) *Nat
ShiftRightVarTime sets x = x >> n.
The announced length of x is unchanged.
func (x *Nat) Sub(y *Nat, m *Modulus) *Nat
Sub computes x = x - y mod m.
The length of both operands must be the same as the modulus. Both operands
must already be reduced modulo m.
func (x *Nat) SubOne(m *Modulus) *Nat
SubOne computes x = x - 1 mod m.
The length of x must be the same as the modulus.
func (x *Nat) TrailingZeroBitsVarTime() uint
TrailingZeroBitsVarTime returns the number of trailing zero bits in x.
func (x *Nat) add(y *Nat) (c uint)
add computes x += y and returns the carry.
Both operands must have the same announced length.
func (x *Nat) assign(on choice, y *Nat) *Nat
assign sets x <- y if on == 1, and does nothing otherwise.
Both operands must have the same announced length.
func (x *Nat) cmpGeq(y *Nat) choice
cmpGeq returns 1 if x >= y, and 0 otherwise.
Both operands must have the same announced length.
func (x *Nat) expand(n int) *Nat
expand expands x to n limbs, leaving its value unchanged.
func (x *Nat) maybeSubtractModulus(always choice, m *Modulus)
maybeSubtractModulus computes x -= m if and only if x >= m or if "always" is
yes.
It can be used to reduce modulo m a value up to 2m - 1, which is a common
range for results computed by higher level operations.
always is usually a carry that indicates that the operation that produced x
overflowed its size, meaning abstractly x > 2^_W*n > m even if x < m.
x and m operands must have the same announced length.
func (x *Nat) montgomeryMul(a *Nat, b *Nat, m *Modulus) *Nat
montgomeryMul calculates x = a * b / R mod m, with R = 2^(_W * n) and n =
len(m.nat.limbs), also known as a Montgomery multiplication.
All inputs should be the same length and already reduced modulo m. x will be
resized to the size of m and overwritten.
func (x *Nat) montgomeryReduction(m *Modulus) *Nat
montgomeryReduction calculates x = x / R mod m, with R = 2^(_W * n) and n =
len(m.nat.limbs).
This assumes that x is already reduced mod m.
func (x *Nat) montgomeryRepresentation(m *Modulus) *Nat
montgomeryRepresentation calculates x = x * R mod m, with R = 2^(_W * n) and
n = len(m.nat.limbs).
Faster Montgomery multiplication replaces standard modular multiplication
for numbers in this representation.
This assumes that x is already reduced mod m.
func (x *Nat) reset(n int) *Nat
reset returns a zero nat of n limbs, reusing x's storage if n <=
cap(x.limbs).
func (out *Nat) resetFor(m *Modulus) *Nat
resetFor ensures out has the right size to work with operations modulo m.
out is zeroed and may start at any size.
func (x *Nat) resetToBytes(b []byte) *Nat
resetToBytes assigns x = b, where b is a slice of big-endian bytes, resizing
n to the appropriate size.
The announced length of x is set based on the actual bit size of the input,
ignoring leading zeroes.
func (x *Nat) set(y *Nat) *Nat
set assigns x = y, optionally resizing x to the appropriate size.
func (x *Nat) setBytes(b []byte) error
func (x *Nat) shiftIn(y uint, m *Modulus) *Nat
shiftIn calculates x = x << _W + y mod m.
This assumes that x is already reduced mod m.
func (x *Nat) sub(y *Nat) (c uint)
sub computes x -= y. It returns the borrow of the subtraction.
Both operands must have the same announced length.
func (x *Nat) trim() *Nat
trim reduces the size of x to match its value.
type choice uint
choice represents a constant-time boolean. The value of choice is always
either 1 or 0. We use an int instead of bool in order to make decisions in
constant time by turning it into a mask.
func ctEq(x, y uint) choice
ctEq returns 1 if x == y, and 0 otherwise. The execution time of this
function does not depend on its inputs.
func not(c choice) choice
crypto/internal/fips140/check
func Enabled() bool
Enabled reports whether verification was enabled. If Enabled returns true,
then verification succeeded, because if it failed the binary would have
panicked at init time.
func Supported() bool
Supported reports whether the current GOOS/GOARCH is Supported at all.
func init()
crypto/internal/fips140/check/checktest
func PtrStaticData() *uint32
func PtrStaticText() unsafe.Pointer
func TEXT()
func init()
crypto/internal/fips140/drbg
func Read(b []byte)
Read fills b with cryptographically secure random bytes. In FIPS mode,
it uses an SP 800-90A Rev. 1 Deterministic Random Bit Generator (DRBG).
Otherwise, it uses the operating system's random number generator.
func ReadWithReader(r io.Reader, b []byte) error
ReadWithReader uses Reader to fill b with cryptographically secure random
bytes. It is intended for use in APIs that expose a rand io.Reader.
If Reader is not the default Reader from crypto/rand, randutil.MaybeReadByte
and fips140.RecordNonApproved are called.
func ReadWithReaderDeterministic(r io.Reader, b []byte) error
ReadWithReaderDeterministic is like ReadWithReader, but it doesn't call
randutil.MaybeReadByte on non-default Readers.
func increment(v *[aes.BlockSize]byte)
func init()
TYPES
type Counter struct {
c aes.CTR
reseedCounter uint64
}
Counter is an SP 800-90A Rev. 1 CTR_DRBG instantiated with AES-256.
Per Table 3, it has a security strength of 256 bits, a seed size of 384
bits, a counter length of 128 bits, a reseed interval of 2^48 requests,
and a maximum request size of 2^19 bits (2^16 bytes, 64 KiB).
We support a narrow range of parameters that fit the needs of our RNG:
AES-256, no derivation function, no personalization string, no prediction
resistance, and 384-bit additional input.
var drbg *Counter
func NewCounter(entropy *[SeedSize]byte) *Counter
func (c *Counter) Generate(out []byte, additionalInput *[SeedSize]byte) (reseedRequired bool)
Generate produces at most maxRequestSize bytes of random data in out.
func (c *Counter) Reseed(entropy, additionalInput *[SeedSize]byte)
func (c *Counter) update(seed *[SeedSize]byte)
type DefaultReader interface{ defaultReader() }
DefaultReader is a sentinel type, embedded in the default
crypto/rand.Reader, used to recognize it when passed to APIs that accept a
rand io.Reader.
crypto/internal/fips140/ecdh
func ECDH[P Point[P]](c *Curve[P], k *PrivateKey, peer *PublicKey) ([]byte, error)
func ecdh[P Point[P]](c *Curve[P], k *PrivateKey, peer *PublicKey) ([]byte, error)
func isLess(a, b []byte) bool
isLess reports whether a < b, where a and b are big-endian buffers of the
same length and shorter than 72 bytes.
func isZero(x []byte) bool
isZero reports whether x is all zeroes in constant time.
TYPES
type Curve[P Point[P]] struct {
curve curveID
newPoint func() P
N []byte
}
func P224() *Curve[*nistec.P224Point]
func P256() *Curve[*nistec.P256Point]
func P384() *Curve[*nistec.P384Point]
func P521() *Curve[*nistec.P521Point]
type Point[P any] interface {
*nistec.P224Point | *nistec.P256Point | *nistec.P384Point | *nistec.P521Point
Bytes() []byte
BytesX() ([]byte, error)
SetBytes([]byte) (P, error)
ScalarMult(P, []byte) (P, error)
ScalarBaseMult([]byte) (P, error)
}
Point is a generic constraint for the nistec Point types.
type PrivateKey struct {
pub PublicKey
}
func GenerateKey[P Point[P]](c *Curve[P], rand io.Reader) (*PrivateKey, error)
GenerateKey generates a new ECDSA private key pair for the specified curve.
func NewPrivateKey[P Point[P]](c *Curve[P], key []byte) (*PrivateKey, error)
func (priv *PrivateKey) Bytes() []byte
func (priv *PrivateKey) PublicKey() *PublicKey
type PublicKey struct {
curve curveID
}
func NewPublicKey[P Point[P]](c *Curve[P], key []byte) (*PublicKey, error)
func (pub *PublicKey) Bytes() []byte
type curveID string
const (
p224 curveID = "P-224"
p256 curveID = "P-256"
p384 curveID = "P-384"
p521 curveID = "P-521"
)
crypto/internal/fips140/ecdsa
func Verify[P Point[P]](c *Curve[P], pub *PublicKey, hash []byte, sig *Signature) error
Verify verifies the signature, sig, of hash (which should be the result of
hashing a larger message) using the public key, pub. If the hash is longer
than the bit-length of the private key's curve order, the hash will be
truncated to that length.
The inputs are not considered confidential, and may leak through timing side
channels, or if an attacker has control of part of the inputs.
func bits2octets[P Point[P]](c *Curve[P], hash []byte) []byte
bits2octets as specified in FIPS 186-5, Appendix B.2.4 or RFC 6979, Section
2.3.4. See RFC 6979, Section 3.5 for the rationale.
func fipsPCT[P Point[P]](c *Curve[P], k *PrivateKey) error
func hashToNat[P Point[P]](c *Curve[P], e *bigmod.Nat, hash []byte)
hashToNat sets e to the left-most bits of hash, according to FIPS 186-5,
Section 6.4.1, point 2 and Section 6.4.2, point 3.
func inverse[P Point[P]](c *Curve[P], kInv, k *bigmod.Nat)
inverse sets kInv to the inverse of k modulo the order of the curve.
func pad000(h *hmac.HMAC, writtenSoFar int)
func precomputeParams[P Point[P]](c *Curve[P], order []byte)
func randomPoint[P Point[P]](c *Curve[P], generate func([]byte) error) (k *bigmod.Nat, p P, err error)
randomPoint returns a random scalar and the corresponding point using
a procedure equivalent to FIPS 186-5, Appendix A.2.2 (ECDSA Key Pair
Generation by Rejection Sampling) and to Appendix A.3.2 (Per-Message Secret
Number Generation of Private Keys by Rejection Sampling) or Appendix A.3.3
(Per-Message Secret Number Generation for Deterministic ECDSA) followed by
Step 5 of Section 6.4.1.
func rightShift(b []byte, shift int) []byte
rightShift implements the right shift necessary for bits2int, which takes
the leftmost bits of either the hash or HMAC_DRBG output.
Note how taking the rightmost bits would have been as easy as masking the
first byte, but we can't have nice things.
func testHash() []byte
func verify[P Point[P]](c *Curve[P], pub *PublicKey, hash []byte, sig *Signature) error
func verifyGeneric[P Point[P]](c *Curve[P], pub *PublicKey, hash []byte, sig *Signature) error
TYPES
type Curve[P Point[P]] struct {
curve curveID
newPoint func() P
ordInverse func([]byte) ([]byte, error)
N *bigmod.Modulus
nMinus2 []byte
}
func P224() *Curve[*nistec.P224Point]
func P256() *Curve[*nistec.P256Point]
func P384() *Curve[*nistec.P384Point]
func P521() *Curve[*nistec.P521Point]
type Point[P any] interface {
*nistec.P224Point | *nistec.P256Point | *nistec.P384Point | *nistec.P521Point
Bytes() []byte
BytesX() ([]byte, error)
SetBytes([]byte) (P, error)
ScalarMult(P, []byte) (P, error)
ScalarBaseMult([]byte) (P, error)
Add(p1, p2 P) P
}
Point is a generic constraint for the nistec Point types.
type PrivateKey struct {
pub PublicKey
}
func GenerateKey[P Point[P]](c *Curve[P], rand io.Reader) (*PrivateKey, error)
GenerateKey generates a new ECDSA private key pair for the specified curve.
func NewPrivateKey[P Point[P]](c *Curve[P], D, Q []byte) (*PrivateKey, error)
func testPrivateKey() *PrivateKey
func (priv *PrivateKey) Bytes() []byte
func (priv *PrivateKey) PublicKey() *PublicKey
type PublicKey struct {
curve curveID
}
func NewPublicKey[P Point[P]](c *Curve[P], Q []byte) (*PublicKey, error)
func (pub *PublicKey) Bytes() []byte
type Signature struct {
R, S []byte
}
Signature is an ECDSA signature, where r and s are represented as big-endian
byte slices of the same length as the curve order.
func Sign[P Point[P], H fips140.Hash](c *Curve[P], h func() H, priv *PrivateKey, rand io.Reader, hash []byte) (*Signature, error)
Sign signs a hash (which shall be the result of hashing a larger message
with the hash function H) using the private key, priv. If the hash is longer
than the bit-length of the private key's curve order, the hash will be
truncated to that length.
func SignDeterministic[P Point[P], H fips140.Hash](c *Curve[P], h func() H, priv *PrivateKey, hash []byte) (*Signature, error)
SignDeterministic signs a hash (which shall be the result of hashing a
larger message with the hash function H) using the private key, priv.
If the hash is longer than the bit-length of the private key's curve order,
the hash will be truncated to that length. This applies Deterministic ECDSA
as specified in FIPS 186-5 and RFC 6979.
func sign[P Point[P]](c *Curve[P], priv *PrivateKey, drbg *hmacDRBG, hash []byte) (*Signature, error)
func signGeneric[P Point[P]](c *Curve[P], priv *PrivateKey, drbg *hmacDRBG, hash []byte) (*Signature, error)
type blockAlignedPersonalizationString [][]byte
Each entry in blockAlignedPersonalizationString is written to the HMAC at
a block boundary, as specified in draft-irtf-cfrg-det-sigs-with-noise-04,
Section 4.
func (blockAlignedPersonalizationString) isPersonalizationString()
type curveID string
const (
p224 curveID = "P-224"
p256 curveID = "P-256"
p384 curveID = "P-384"
p521 curveID = "P-521"
)
type hmacDRBG struct {
newHMAC func(key []byte) *hmac.HMAC
hK *hmac.HMAC
V []byte
reseedCounter uint64
}
hmacDRBG is an SP 800-90A Rev. 1 HMAC_DRBG.
It is only intended to be used to generate ECDSA nonces. Since it will be
instantiated ex-novo for each signature, its Generate function will only be
invoked once or twice (only for P-256, with probability 2⁻³²).
Per Table 2, it has a reseed interval of 2^48 requests, and a maximum
request size of 2^19 bits (2^16 bytes, 64 KiB).
func newDRBG[H fips140.Hash](hash func() H, entropy, nonce []byte, s personalizationString) *hmacDRBG
func (d *hmacDRBG) Generate(out []byte)
Generate produces at most maxRequestSize bytes of random data in out.
type personalizationString interface {
isPersonalizationString()
}
type plainPersonalizationString []byte
plainPersonalizationString is used by HMAC_DRBG as-is.
func (plainPersonalizationString) isPersonalizationString()
crypto/internal/fips140/ed25519
func Sign(priv *PrivateKey, message []byte) []byte
func SignCtx(priv *PrivateKey, message []byte, context string) ([]byte, error)
func SignPH(priv *PrivateKey, message []byte, context string) ([]byte, error)
func Verify(pub *PublicKey, message, sig []byte) error
func VerifyCtx(pub *PublicKey, message []byte, sig []byte, context string) error
func VerifyPH(pub *PublicKey, message []byte, sig []byte, context string) error
func fipsPCT(k *PrivateKey) error
func pairwiseTest(k *PrivateKey) error
pairwiseTest needs to be a top-level function declaration to let the calls
inline and their allocations not escape.
func precomputePrivateKey(priv *PrivateKey)
func sign(signature []byte, priv *PrivateKey, message []byte) []byte
func signCtx(signature []byte, priv *PrivateKey, message []byte, context string) ([]byte, error)
func signPH(signature []byte, priv *PrivateKey, message []byte, context string) ([]byte, error)
func signWithDom(signature []byte, priv *PrivateKey, message []byte, domPrefix, context string) []byte
func signWithoutSelfTest(priv *PrivateKey, message []byte) []byte
func verify(pub *PublicKey, message, sig []byte) error
func verifyWithDom(pub *PublicKey, message, sig []byte, domPrefix, context string) error
func verifyWithoutSelfTest(pub *PublicKey, message, sig []byte) error
TYPES
type PrivateKey struct {
seed [seedSize]byte
pub [publicKeySize]byte
s edwards25519.Scalar
prefix [sha512Size / 2]byte
}
func GenerateKey() (*PrivateKey, error)
GenerateKey generates a new Ed25519 private key pair.
func NewPrivateKey(priv []byte) (*PrivateKey, error)
func NewPrivateKeyFromSeed(seed []byte) (*PrivateKey, error)
func generateKey(priv *PrivateKey) (*PrivateKey, error)
func newPrivateKey(priv *PrivateKey, privBytes []byte) (*PrivateKey, error)
func newPrivateKeyFromSeed(priv *PrivateKey, seed []byte) (*PrivateKey, error)
func (priv *PrivateKey) Bytes() []byte
func (priv *PrivateKey) PublicKey() []byte
func (priv *PrivateKey) Seed() []byte
type PublicKey struct {
a edwards25519.Point
aBytes [32]byte
}
func NewPublicKey(pub []byte) (*PublicKey, error)
func newPublicKey(pub *PublicKey, pubBytes []byte) (*PublicKey, error)
func (pub *PublicKey) Bytes() []byte
crypto/internal/fips140/edwards25519
func basepointTable() *[32]affineLookupTable
basepointTable is a set of 32 affineLookupTables, where table i is generated
from 256i * basepoint. It is precomputed the first time it's used.
func checkInitialized(points ...*Point)
func copyFieldElement(buf *[32]byte, v *field.Element) []byte
func fiatScalarAdd(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement, arg2 *fiatScalarMontgomeryDomainFieldElement)
fiatScalarAdd adds two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func fiatScalarCmovznzU64(out1 *uint64, arg1 fiatScalarUint1, arg2 uint64, arg3 uint64)
fiatScalarCmovznzU64 is a single-word conditional move.
Postconditions:
out1 = (if arg1 = 0 then arg2 else arg3)
Input Bounds:
arg1: [0x0 ~> 0x1]
arg2: [0x0 ~> 0xffffffffffffffff]
arg3: [0x0 ~> 0xffffffffffffffff]
Output Bounds:
out1: [0x0 ~> 0xffffffffffffffff]
func fiatScalarFromBytes(out1 *[4]uint64, arg1 *[32]uint8)
fiatScalarFromBytes deserializes a field element NOT in the Montgomery
domain from bytes in little-endian order.
Preconditions:
0 ≤ bytes_eval arg1 < m
Postconditions:
eval out1 mod m = bytes_eval arg1 mod m
0 ≤ eval out1 < m
Input Bounds:
arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x1f]]
Output Bounds:
out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x1fffffffffffffff]]
func fiatScalarFromMontgomery(out1 *fiatScalarNonMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement)
fiatScalarFromMontgomery translates a field element out of the Montgomery
domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m
0 ≤ eval out1 < m
func fiatScalarMul(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement, arg2 *fiatScalarMontgomeryDomainFieldElement)
fiatScalarMul multiplies two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func fiatScalarNonzero(out1 *uint64, arg1 *[4]uint64)
fiatScalarNonzero outputs a single non-zero word if the input is non-zero
and zero otherwise.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0
Input Bounds:
arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
Output Bounds:
out1: [0x0 ~> 0xffffffffffffffff]
func fiatScalarOpp(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement)
fiatScalarOpp negates a field element in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m
0 ≤ eval out1 < m
func fiatScalarSub(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarMontgomeryDomainFieldElement, arg2 *fiatScalarMontgomeryDomainFieldElement)
fiatScalarSub subtracts two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func fiatScalarToBytes(out1 *[32]uint8, arg1 *[4]uint64)
fiatScalarToBytes serializes a field element NOT in the Montgomery domain to
bytes in little-endian order.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31]
Input Bounds:
arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x1fffffffffffffff]]
Output Bounds:
out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x1f]]
func fiatScalarToMontgomery(out1 *fiatScalarMontgomeryDomainFieldElement, arg1 *fiatScalarNonMontgomeryDomainFieldElement)
fiatScalarToMontgomery translates a field element into the Montgomery
domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = eval arg1 mod m
0 ≤ eval out1 < m
func isReduced(s []byte) bool
isReduced returns whether the given scalar in 32-byte little endian encoded
form is reduced modulo l.
TYPES
type Point struct {
_ incomparable
x, y, z, t field.Element
}
Point represents a point on the edwards25519 curve.
This type works similarly to math/big.Int, and all arguments and receivers
are allowed to alias.
The zero value is NOT valid, and it may be used only as a receiver.
func NewGeneratorPoint() *Point
NewGeneratorPoint returns a new Point set to the canonical generator.
func NewIdentityPoint() *Point
NewIdentityPoint returns a new Point set to the identity.
func (v *Point) Add(p, q *Point) *Point
Add sets v = p + q, and returns v.
func (v *Point) Bytes() []byte
Bytes returns the canonical 32-byte encoding of v, according to RFC 8032,
Section 5.1.2.
func (v *Point) Equal(u *Point) int
Equal returns 1 if v is equivalent to u, and 0 otherwise.
func (v *Point) Negate(p *Point) *Point
Negate sets v = -p, and returns v.
func (v *Point) ScalarBaseMult(x *Scalar) *Point
ScalarBaseMult sets v = x * B, where B is the canonical generator, and
returns v.
The scalar multiplication is done in constant time.
func (v *Point) ScalarMult(x *Scalar, q *Point) *Point
ScalarMult sets v = x * q, and returns v.
The scalar multiplication is done in constant time.
func (v *Point) Set(u *Point) *Point
Set sets v = u, and returns v.
func (v *Point) SetBytes(x []byte) (*Point, error)
SetBytes sets v = x, where x is a 32-byte encoding of v. If x does not
represent a valid point on the curve, SetBytes returns nil and an error and
the receiver is unchanged. Otherwise, SetBytes returns v.
Note that SetBytes accepts all non-canonical encodings of valid points.
That is, it follows decoding rules that match most implementations in the
ecosystem rather than RFC 8032.
func (v *Point) Subtract(p, q *Point) *Point
Subtract sets v = p - q, and returns v.
func (v *Point) VarTimeDoubleScalarBaseMult(a *Scalar, A *Point, b *Scalar) *Point
VarTimeDoubleScalarBaseMult sets v = a * A + b * B, where B is the canonical
generator, and returns v.
Execution time depends on the inputs.
func (v *Point) bytes(buf *[32]byte) []byte
func (v *Point) fromP1xP1(p *projP1xP1) *Point
func (v *Point) fromP2(p *projP2) *Point
type Scalar struct {
s fiatScalarMontgomeryDomainFieldElement
}
A Scalar is an integer modulo
l = 2^252 + 27742317777372353535851937790883648493
which is the prime order of the edwards25519 group.
This type works similarly to math/big.Int, and all arguments and receivers
are allowed to alias.
The zero value is a valid zero element.
func NewScalar() *Scalar
NewScalar returns a new zero Scalar.
func (s *Scalar) Add(x, y *Scalar) *Scalar
Add sets s = x + y mod l, and returns s.
func (s *Scalar) Bytes() []byte
Bytes returns the canonical 32-byte little-endian encoding of s.
func (s *Scalar) Equal(t *Scalar) int
Equal returns 1 if s and t are equal, and 0 otherwise.
func (s *Scalar) Multiply(x, y *Scalar) *Scalar
Multiply sets s = x * y mod l, and returns s.
func (s *Scalar) MultiplyAdd(x, y, z *Scalar) *Scalar
MultiplyAdd sets s = x * y + z mod l, and returns s. It is equivalent to
using Multiply and then Add.
func (s *Scalar) Negate(x *Scalar) *Scalar
Negate sets s = -x mod l, and returns s.
func (s *Scalar) Set(x *Scalar) *Scalar
Set sets s = x, and returns s.
func (s *Scalar) SetBytesWithClamping(x []byte) (*Scalar, error)
SetBytesWithClamping applies the buffer pruning described in RFC 8032,
Section 5.1.5 (also known as clamping) and sets s to the result. The input
must be 32 bytes, and it is not modified. If x is not of the right length,
SetBytesWithClamping returns nil and an error, and the receiver is
unchanged.
Note that since Scalar values are always reduced modulo the prime
order of the curve, the resulting value will not preserve any of the
cofactor-clearing properties that clamping is meant to provide. It will
however work as expected as long as it is applied to points on the prime
order subgroup, like in Ed25519. In fact, it is lost to history why RFC
8032 adopted the irrelevant RFC 7748 clamping, but it is now required for
compatibility.
func (s *Scalar) SetCanonicalBytes(x []byte) (*Scalar, error)
SetCanonicalBytes sets s = x, where x is a 32-byte little-endian encoding of
s, and returns s. If x is not a canonical encoding of s, SetCanonicalBytes
returns nil and an error, and the receiver is unchanged.
func (s *Scalar) SetUniformBytes(x []byte) (*Scalar, error)
SetUniformBytes sets s = x mod l, where x is a 64-byte little-endian
integer. If x is not of the right length, SetUniformBytes returns nil and an
error, and the receiver is unchanged.
SetUniformBytes can be used to set s to a uniformly distributed value given
64 uniformly distributed random bytes.
func (s *Scalar) Subtract(x, y *Scalar) *Scalar
Subtract sets s = x - y mod l, and returns s.
func (s *Scalar) bytes(out *[32]byte) []byte
func (s *Scalar) nonAdjacentForm(w uint) [256]int8
nonAdjacentForm computes a width-w non-adjacent form for this scalar.
w must be between 2 and 8, or nonAdjacentForm will panic.
func (s *Scalar) setShortBytes(x []byte) *Scalar
setShortBytes sets s = x mod l, where x is a little-endian integer shorter
than 32 bytes.
func (s *Scalar) signedRadix16() [64]int8
type affineCached struct {
YplusX, YminusX, T2d field.Element
}
func (v *affineCached) CondNeg(cond int) *affineCached
CondNeg negates v if cond == 1 and leaves it unchanged if cond == 0.
func (v *affineCached) FromP3(p *Point) *affineCached
func (v *affineCached) Select(a, b *affineCached, cond int) *affineCached
Select sets v to a if cond == 1 and to b if cond == 0.
func (v *affineCached) Zero() *affineCached
type affineLookupTable struct {
points [8]affineCached
}
A precomputed lookup table for fixed-base, constant-time scalar muls.
func (v *affineLookupTable) FromP3(q *Point)
This is not optimised for speed; fixed-base tables should be precomputed.
func (v *affineLookupTable) SelectInto(dest *affineCached, x int8)
Set dest to x*Q, where -8 <= x <= 8, in constant time.
type fiatScalarMontgomeryDomainFieldElement [4]uint64
The type fiatScalarMontgomeryDomainFieldElement is a field element in the
Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
type fiatScalarNonMontgomeryDomainFieldElement [4]uint64
The type fiatScalarNonMontgomeryDomainFieldElement is a field element NOT in
the Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
type incomparable [0]func()
type nafLookupTable5 struct {
points [8]projCached
}
A dynamic lookup table for variable-base, variable-time scalar muls.
func (v *nafLookupTable5) FromP3(q *Point)
Builds a lookup table at runtime. Fast.
func (v *nafLookupTable5) SelectInto(dest *projCached, x int8)
Given odd x with 0 < x < 2^4, return x*Q (in variable time).
type nafLookupTable8 struct {
points [64]affineCached
}
A precomputed lookup table for fixed-base, variable-time scalar muls.
func basepointNafTable() *nafLookupTable8
basepointNafTable is the nafLookupTable8 for the basepoint. It is
precomputed the first time it's used.
func (v *nafLookupTable8) FromP3(q *Point)
This is not optimised for speed; fixed-base tables should be precomputed.
func (v *nafLookupTable8) SelectInto(dest *affineCached, x int8)
Given odd x with 0 < x < 2^7, return x*Q (in variable time).
type projCached struct {
YplusX, YminusX, Z, T2d field.Element
}
func (v *projCached) CondNeg(cond int) *projCached
CondNeg negates v if cond == 1 and leaves it unchanged if cond == 0.
func (v *projCached) FromP3(p *Point) *projCached
func (v *projCached) Select(a, b *projCached, cond int) *projCached
Select sets v to a if cond == 1 and to b if cond == 0.
func (v *projCached) Zero() *projCached
type projLookupTable struct {
points [8]projCached
}
A dynamic lookup table for variable-base, constant-time scalar muls.
func (v *projLookupTable) FromP3(q *Point)
Builds a lookup table at runtime. Fast.
func (v *projLookupTable) SelectInto(dest *projCached, x int8)
Set dest to x*Q, where -8 <= x <= 8, in constant time.
type projP1xP1 struct {
X, Y, Z, T field.Element
}
func (v *projP1xP1) Add(p *Point, q *projCached) *projP1xP1
func (v *projP1xP1) AddAffine(p *Point, q *affineCached) *projP1xP1
func (v *projP1xP1) Double(p *projP2) *projP1xP1
func (v *projP1xP1) Sub(p *Point, q *projCached) *projP1xP1
func (v *projP1xP1) SubAffine(p *Point, q *affineCached) *projP1xP1
type projP2 struct {
X, Y, Z field.Element
}
func (v *projP2) FromP1xP1(p *projP1xP1) *projP2
func (v *projP2) FromP3(p *Point) *projP2
func (v *projP2) Zero() *projP2
crypto/internal/fips140/edwards25519/field
func feMul(out *Element, a *Element, b *Element)
feMul sets out = a * b. It works like feMulGeneric.
func feMulGeneric(v, a, b *Element)
func feSquare(out *Element, a *Element)
feSquare sets out = a * a. It works like feSquareGeneric.
func feSquareGeneric(v, a *Element)
func mask64Bits(cond int) uint64
mask64Bits returns 0xffffffff if cond is 1, and 0 otherwise.
func mul51(a uint64, b uint32) (lo uint64, hi uint64)
mul51 returns lo + hi * 2⁵¹ = a * b.
func shiftRightBy51(a uint128) uint64
shiftRightBy51 returns a >> 51. a is assumed to be at most 115 bits.
TYPES
type Element struct {
l0 uint64
l1 uint64
l2 uint64
l3 uint64
l4 uint64
}
Element represents an element of the field GF(2^255-19). Note that this is
not a cryptographically secure group, and should only be used to interact
with edwards25519.Point coordinates.
This type works similarly to math/big.Int, and all arguments and receivers
are allowed to alias.
The zero value is a valid zero element.
func (v *Element) Absolute(u *Element) *Element
Absolute sets v to |u|, and returns v.
func (v *Element) Add(a, b *Element) *Element
Add sets v = a + b, and returns v.
func (v *Element) Bytes() []byte
Bytes returns the canonical 32-byte little-endian encoding of v.
func (v *Element) Equal(u *Element) int
Equal returns 1 if v and u are equal, and 0 otherwise.
func (v *Element) Invert(z *Element) *Element
Invert sets v = 1/z mod p, and returns v.
If z == 0, Invert returns v = 0.
func (v *Element) IsNegative() int
IsNegative returns 1 if v is negative, and 0 otherwise.
func (v *Element) Mult32(x *Element, y uint32) *Element
Mult32 sets v = x * y, and returns v.
func (v *Element) Multiply(x, y *Element) *Element
Multiply sets v = x * y, and returns v.
func (v *Element) Negate(a *Element) *Element
Negate sets v = -a, and returns v.
func (v *Element) One() *Element
One sets v = 1, and returns v.
func (v *Element) Pow22523(x *Element) *Element
Pow22523 set v = x^((p-5)/8), and returns v. (p-5)/8 is 2^252-3.
func (v *Element) Select(a, b *Element, cond int) *Element
Select sets v to a if cond == 1, and to b if cond == 0.
func (v *Element) Set(a *Element) *Element
Set sets v = a, and returns v.
func (v *Element) SetBytes(x []byte) (*Element, error)
SetBytes sets v to x, where x is a 32-byte little-endian encoding. If x is
not of the right length, SetBytes returns nil and an error, and the receiver
is unchanged.
Consistent with RFC 7748, the most significant bit (the high bit of the last
byte) is ignored, and non-canonical values (2^255-19 through 2^255-1) are
accepted. Note that this is laxer than specified by RFC 8032, but consistent
with most Ed25519 implementations.
func (r *Element) SqrtRatio(u, v *Element) (R *Element, wasSquare int)
SqrtRatio sets r to the non-negative square root of the ratio of u and v.
If u/v is square, SqrtRatio returns r and 1. If u/v is not square, SqrtRatio
sets r according to Section 4.3 of draft-irtf-cfrg-ristretto255-decaf448-00,
and returns r and 0.
func (v *Element) Square(x *Element) *Element
Square sets v = x * x, and returns v.
func (v *Element) Subtract(a, b *Element) *Element
Subtract sets v = a - b, and returns v.
func (v *Element) Swap(u *Element, cond int)
Swap swaps v and u if cond == 1 or leaves them unchanged if cond == 0,
and returns v.
func (v *Element) Zero() *Element
Zero sets v = 0, and returns v.
func (v *Element) bytes(out *[32]byte) []byte
func (v *Element) carryPropagate() *Element
func (v *Element) carryPropagateGeneric() *Element
carryPropagateGeneric brings the limbs below 52 bits by applying the
reduction identity (a * 2²⁵⁵ + b = a * 19 + b) to the l4 carry.
func (v *Element) reduce() *Element
reduce reduces v modulo 2^255 - 19 and returns it.
type uint128 struct {
lo, hi uint64
}
uint128 holds a 128-bit number as two 64-bit limbs, for use with the
bits.Mul64 and bits.Add64 intrinsics.
func addMul64(v uint128, a, b uint64) uint128
addMul64 returns v + a * b.
func mul64(a, b uint64) uint128
mul64 returns a * b.
crypto/internal/fips140/hkdf
func Expand[H fips140.Hash](h func() H, pseudorandomKey []byte, info string, keyLen int) []byte
func Extract[H fips140.Hash](h func() H, secret, salt []byte) []byte
func Key[H fips140.Hash](h func() H, secret, salt []byte, info string, keyLen int) []byte
func init()
crypto/internal/fips140/hmac
func MarkAsUsedInKDF(h *HMAC)
MarkAsUsedInKDF records that this HMAC instance is used as part of a KDF.
func init()
TYPES
type HMAC struct {
opad, ipad []byte
outer, inner fips140.Hash
marshaled bool
forHKDF bool
keyLen int
}
func New[H fips140.Hash](h func() H, key []byte) *HMAC
New returns a new HMAC hash using the given fips140.Hash type and key.
func (h *HMAC) BlockSize() int
func (h *HMAC) Reset()
func (h *HMAC) Size() int
func (h *HMAC) Sum(in []byte) []byte
func (h *HMAC) Write(p []byte) (n int, err error)
type marshalable interface {
MarshalBinary() ([]byte, error)
UnmarshalBinary([]byte) error
}
marshalable is the combination of encoding.BinaryMarshaler and
encoding.BinaryUnmarshaler. Their method definitions are repeated here to
avoid a dependency on the encoding package.
crypto/internal/fips140/mlkem
func compress(x fieldElement, d uint8) uint16
compress maps a field element uniformly to the range 0 to 2ᵈ-1, according to
FIPS 203, Definition 4.7.
func init()
func kemDecaps(dk *DecapsulationKey768, c *[CiphertextSize768]byte) (K []byte)
kemDecaps produces a shared key from a ciphertext.
It implements ML-KEM.Decaps_internal according to FIPS 203, Algorithm 18.
func kemDecaps1024(dk *DecapsulationKey1024, c *[CiphertextSize1024]byte) (K []byte)
kemDecaps1024 produces a shared key from a ciphertext.
It implements ML-KEM.Decaps_internal according to FIPS 203, Algorithm 18.
func kemEncaps(cc *[CiphertextSize768]byte, ek *EncapsulationKey768, m *[messageSize]byte) (c, K []byte)
kemEncaps generates a shared key and an associated ciphertext.
It implements ML-KEM.Encaps_internal according to FIPS 203, Algorithm 17.
func kemEncaps1024(cc *[CiphertextSize1024]byte, ek *EncapsulationKey1024, m *[messageSize]byte) (c, K []byte)
kemEncaps1024 generates a shared key and an associated ciphertext.
It implements ML-KEM.Encaps_internal according to FIPS 203, Algorithm 17.
func kemKeyGen(dk *DecapsulationKey768, d, z *[32]byte)
kemKeyGen generates a decapsulation key.
It implements ML-KEM.KeyGen_internal according to FIPS 203, Algorithm 16,
and K-PKE.KeyGen according to FIPS 203, Algorithm 13. The two are merged to
save copies and allocations.
func kemKeyGen1024(dk *DecapsulationKey1024, d, z *[32]byte)
kemKeyGen1024 generates a decapsulation key.
It implements ML-KEM.KeyGen_internal according to FIPS 203, Algorithm 16,
and K-PKE.KeyGen according to FIPS 203, Algorithm 13. The two are merged to
save copies and allocations.
func kemPCT(dk *DecapsulationKey768) error
kemPCT performs a Pairwise Consistency Test per FIPS 140-3 IG 10.3.A
Additional Comment 1: "For key pairs generated for use with approved KEMs
in FIPS 203, the PCT shall consist of applying the encapsulation key ek to
encapsulate a shared secret K leading to ciphertext c, and then applying
decapsulation key dk to retrieve the same shared secret K. The PCT passes if
the two shared secret K values are equal. The PCT shall be performed either
when keys are generated/imported, prior to the first exportation, or prior
to the first operational use (if not exported before the first use)."
func kemPCT1024(dk *DecapsulationKey1024) error
kemPCT1024 performs a Pairwise Consistency Test per FIPS 140-3 IG 10.3.A
Additional Comment 1: "For key pairs generated for use with approved KEMs
in FIPS 203, the PCT shall consist of applying the encapsulation key ek to
encapsulate a shared secret K leading to ciphertext c, and then applying
decapsulation key dk to retrieve the same shared secret K. The PCT passes if
the two shared secret K values are equal. The PCT shall be performed either
when keys are generated/imported, prior to the first exportation, or prior
to the first operational use (if not exported before the first use)."
func pkeDecrypt(dx *decryptionKey, c *[CiphertextSize768]byte) []byte
pkeDecrypt decrypts a ciphertext.
It implements K-PKE.Decrypt according to FIPS 203, Algorithm 15, although s
is retained from kemKeyGen.
func pkeDecrypt1024(dx *decryptionKey1024, c *[CiphertextSize1024]byte) []byte
pkeDecrypt1024 decrypts a ciphertext.
It implements K-PKE.Decrypt according to FIPS 203, Algorithm 15, although s
is retained from kemKeyGen1024.
func pkeEncrypt(cc *[CiphertextSize768]byte, ex *encryptionKey, m *[messageSize]byte, rnd []byte) []byte
pkeEncrypt encrypt a plaintext message.
It implements K-PKE.Encrypt according to FIPS 203, Algorithm 14, although
the computation of t and AT is done in parseEK.
func pkeEncrypt1024(cc *[CiphertextSize1024]byte, ex *encryptionKey1024, m *[messageSize]byte, rnd []byte) []byte
pkeEncrypt1024 encrypt a plaintext message.
It implements K-PKE.Encrypt according to FIPS 203, Algorithm 14, although
the computation of t and AT is done in parseEK1024.
func polyAdd[T ~[n]fieldElement](a, b T) (s T)
polyAdd adds two ringElements or nttElements.
func polyByteDecode[T ~[n]fieldElement](b []byte) (T, error)
polyByteDecode decodes the 384-byte encoding of a polynomial, checking that
all the coefficients are properly reduced. This fulfills the "Modulus check"
step of ML-KEM Encapsulation.
It implements ByteDecode₁₂, according to FIPS 203, Algorithm 6.
func polyByteEncode[T ~[n]fieldElement](b []byte, f T) []byte
polyByteEncode appends the 384-byte encoding of f to b.
It implements ByteEncode₁₂, according to FIPS 203, Algorithm 5.
func polySub[T ~[n]fieldElement](a, b T) (s T)
polySub subtracts two ringElements or nttElements.
func ringCompressAndEncode(s []byte, f ringElement, d uint8) []byte
ringCompressAndEncode appends an encoding of a ring element to s,
compressing each coefficient to d bits.
It implements Compress, according to FIPS 203, Definition 4.7, followed by
ByteEncode, according to FIPS 203, Algorithm 5.
func ringCompressAndEncode1(s []byte, f ringElement) []byte
ringCompressAndEncode1 appends a 32-byte encoding of a ring element to s,
compressing one coefficients per bit.
It implements Compress₁, according to FIPS 203, Definition 4.7, followed by
ByteEncode₁, according to FIPS 203, Algorithm 5.
func ringCompressAndEncode10(s []byte, f ringElement) []byte
ringCompressAndEncode10 appends a 320-byte encoding of a ring element to s,
compressing four coefficients per five bytes.
It implements Compress₁₀, according to FIPS 203, Definition 4.7, followed by
ByteEncode₁₀, according to FIPS 203, Algorithm 5.
func ringCompressAndEncode11(s []byte, f ringElement) []byte
ringCompressAndEncode11 appends a 352-byte encoding of a ring element to s,
compressing eight coefficients per eleven bytes.
It implements Compress₁₁, according to FIPS 203, Definition 4.7, followed by
ByteEncode₁₁, according to FIPS 203, Algorithm 5.
func ringCompressAndEncode4(s []byte, f ringElement) []byte
ringCompressAndEncode4 appends a 128-byte encoding of a ring element to s,
compressing two coefficients per byte.
It implements Compress₄, according to FIPS 203, Definition 4.7, followed by
ByteEncode₄, according to FIPS 203, Algorithm 5.
func ringCompressAndEncode5(s []byte, f ringElement) []byte
ringCompressAndEncode5 appends a 160-byte encoding of a ring element to s,
compressing eight coefficients per five bytes.
It implements Compress₅, according to FIPS 203, Definition 4.7, followed by
ByteEncode₅, according to FIPS 203, Algorithm 5.
func sliceForAppend(in []byte, n int) (head, tail []byte)
sliceForAppend takes a slice and a requested number of bytes. It returns a
slice with the contents of the given slice followed by that many bytes and a
second slice that aliases into it and contains only the extra bytes. If the
original slice has sufficient capacity then no allocation is performed.
TYPES
type DecapsulationKey1024 struct {
encryptionKey1024
decryptionKey1024
}
A DecapsulationKey1024 is the secret key used to decapsulate a shared key
from a ciphertext. It includes various precomputed values.
func GenerateKey1024() (*DecapsulationKey1024, error)
GenerateKey1024 generates a new decapsulation key, drawing random bytes from
a DRBG. The decapsulation key must be kept secret.
func GenerateKeyInternal1024(d, z *[32]byte) *DecapsulationKey1024
GenerateKeyInternal1024 is a derandomized version of GenerateKey1024,
exclusively for use in tests.
func NewDecapsulationKey1024(seed []byte) (*DecapsulationKey1024, error)
NewDecapsulationKey1024 parses a decapsulation key from a 64-byte seed in
the "d || z" form. The seed must be uniformly random.
func generateKey1024(dk *DecapsulationKey1024) (*DecapsulationKey1024, error)
func newKeyFromSeed1024(dk *DecapsulationKey1024, seed []byte) (*DecapsulationKey1024, error)
func (dk *DecapsulationKey1024) Bytes() []byte
Bytes returns the decapsulation key as a 64-byte seed in the "d || z" form.
The decapsulation key must be kept secret.
func (dk *DecapsulationKey1024) Decapsulate(ciphertext []byte) (sharedKey []byte, err error)
Decapsulate generates a shared key from a ciphertext and a decapsulation
key. If the ciphertext is not valid, Decapsulate returns an error.
The shared key must be kept secret.
func (dk *DecapsulationKey1024) EncapsulationKey() *EncapsulationKey1024
EncapsulationKey returns the public encapsulation key necessary to produce
ciphertexts.
type DecapsulationKey768 struct {
encryptionKey
decryptionKey
}
A DecapsulationKey768 is the secret key used to decapsulate a shared key
from a ciphertext. It includes various precomputed values.
func GenerateKey768() (*DecapsulationKey768, error)
GenerateKey768 generates a new decapsulation key, drawing random bytes from
a DRBG. The decapsulation key must be kept secret.
func GenerateKeyInternal768(d, z *[32]byte) *DecapsulationKey768
GenerateKeyInternal768 is a derandomized version of GenerateKey768,
exclusively for use in tests.
func NewDecapsulationKey768(seed []byte) (*DecapsulationKey768, error)
NewDecapsulationKey768 parses a decapsulation key from a 64-byte seed in the
"d || z" form. The seed must be uniformly random.
func generateKey(dk *DecapsulationKey768) (*DecapsulationKey768, error)
func newKeyFromSeed(dk *DecapsulationKey768, seed []byte) (*DecapsulationKey768, error)
func (dk *DecapsulationKey768) Bytes() []byte
Bytes returns the decapsulation key as a 64-byte seed in the "d || z" form.
The decapsulation key must be kept secret.
func (dk *DecapsulationKey768) Decapsulate(ciphertext []byte) (sharedKey []byte, err error)
Decapsulate generates a shared key from a ciphertext and a decapsulation
key. If the ciphertext is not valid, Decapsulate returns an error.
The shared key must be kept secret.
func (dk *DecapsulationKey768) EncapsulationKey() *EncapsulationKey768
EncapsulationKey returns the public encapsulation key necessary to produce
ciphertexts.
type EncapsulationKey1024 struct {
encryptionKey1024
}
An EncapsulationKey1024 is the public key used to produce ciphertexts to be
decapsulated by the corresponding DecapsulationKey1024.
func NewEncapsulationKey1024(encapsulationKey []byte) (*EncapsulationKey1024, error)
NewEncapsulationKey1024 parses an encapsulation key from its encoded form.
If the encapsulation key is not valid, NewEncapsulationKey1024 returns an
error.
func parseEK1024(ek *EncapsulationKey1024, ekPKE []byte) (*EncapsulationKey1024, error)
parseEK1024 parses an encryption key from its encoded form.
It implements the initial stages of K-PKE.Encrypt according to FIPS 203,
Algorithm 14.
func (ek *EncapsulationKey1024) Bytes() []byte
Bytes returns the encapsulation key as a byte slice.
func (ek *EncapsulationKey1024) Encapsulate() (ciphertext, sharedKey []byte)
Encapsulate generates a shared key and an associated ciphertext from an
encapsulation key, drawing random bytes from a DRBG.
The shared key must be kept secret.
func (ek *EncapsulationKey1024) EncapsulateInternal(m *[32]byte) (ciphertext, sharedKey []byte)
EncapsulateInternal is a derandomized version of Encapsulate, exclusively
for use in tests.
func (ek *EncapsulationKey1024) bytes(b []byte) []byte
func (ek *EncapsulationKey1024) encapsulate(cc *[CiphertextSize1024]byte) (ciphertext, sharedKey []byte)
type EncapsulationKey768 struct {
encryptionKey
}
An EncapsulationKey768 is the public key used to produce ciphertexts to be
decapsulated by the corresponding DecapsulationKey768.
func NewEncapsulationKey768(encapsulationKey []byte) (*EncapsulationKey768, error)
NewEncapsulationKey768 parses an encapsulation key from its encoded form. If
the encapsulation key is not valid, NewEncapsulationKey768 returns an error.
func parseEK(ek *EncapsulationKey768, ekPKE []byte) (*EncapsulationKey768, error)
parseEK parses an encryption key from its encoded form.
It implements the initial stages of K-PKE.Encrypt according to FIPS 203,
Algorithm 14.
func (ek *EncapsulationKey768) Bytes() []byte
Bytes returns the encapsulation key as a byte slice.
func (ek *EncapsulationKey768) Encapsulate() (ciphertext, sharedKey []byte)
Encapsulate generates a shared key and an associated ciphertext from an
encapsulation key, drawing random bytes from a DRBG.
The shared key must be kept secret.
func (ek *EncapsulationKey768) EncapsulateInternal(m *[32]byte) (ciphertext, sharedKey []byte)
EncapsulateInternal is a derandomized version of Encapsulate, exclusively
for use in tests.
func (ek *EncapsulationKey768) bytes(b []byte) []byte
func (ek *EncapsulationKey768) encapsulate(cc *[CiphertextSize768]byte) (ciphertext, sharedKey []byte)
type decryptionKey struct {
}
decryptionKey is the parsed and expanded form of a PKE decryption key.
type decryptionKey1024 struct {
}
decryptionKey1024 is the parsed and expanded form of a PKE decryption key.
type encryptionKey struct {
}
encryptionKey is the parsed and expanded form of a PKE encryption key.
type encryptionKey1024 struct {
}
encryptionKey1024 is the parsed and expanded form of a PKE encryption key.
type fieldElement uint16
fieldElement is an integer modulo q, an element of ℤ_q. It is always
reduced.
func decompress(y uint16, d uint8) fieldElement
decompress maps a number x between 0 and 2ᵈ-1 uniformly to the full range of
field elements, according to FIPS 203, Definition 4.8.
func fieldAdd(a, b fieldElement) fieldElement
func fieldAddMul(a, b, c, d fieldElement) fieldElement
fieldAddMul returns a * b + c * d. This operation is fused to save a
fieldReduceOnce and a fieldReduce.
func fieldCheckReduced(a uint16) (fieldElement, error)
fieldCheckReduced checks that a value a is < q.
func fieldMul(a, b fieldElement) fieldElement
func fieldMulSub(a, b, c fieldElement) fieldElement
fieldMulSub returns a * (b - c). This operation is fused to save a
fieldReduceOnce after the subtraction.
func fieldReduce(a uint32) fieldElement
fieldReduce reduces a value a < 2q² using Barrett reduction, to avoid
potentially variable-time division.
func fieldReduceOnce(a uint16) fieldElement
fieldReduceOnce reduces a value a < 2q.
func fieldSub(a, b fieldElement) fieldElement
type nttElement [n]fieldElement
nttElement is an NTT representation, an element of T_q, represented as an
array according to FIPS 203, Section 2.4.4.
func ntt(f ringElement) nttElement
ntt maps a ringElement to its nttElement representation.
It implements NTT, according to FIPS 203, Algorithm 9.
func nttMul(f, g nttElement) nttElement
nttMul multiplies two nttElements.
It implements MultiplyNTTs, according to FIPS 203, Algorithm 11.
func sampleNTT(rho []byte, ii, jj byte) nttElement
sampleNTT draws a uniformly random nttElement from a stream of uniformly
random bytes generated by the XOF function, according to FIPS 203, Algorithm
7.
type ringElement [n]fieldElement
ringElement is a polynomial, an element of R_q, represented as an array
according to FIPS 203, Section 2.4.4.
func inverseNTT(f nttElement) ringElement
inverseNTT maps a nttElement back to the ringElement it represents.
It implements NTT⁻¹, according to FIPS 203, Algorithm 10.
func ringDecodeAndDecompress(b []byte, d uint8) ringElement
ringDecodeAndDecompress decodes an encoding of a ring element where each d
bits are mapped to an equidistant distribution.
It implements ByteDecode, according to FIPS 203, Algorithm 6, followed by
Decompress, according to FIPS 203, Definition 4.8.
func ringDecodeAndDecompress1(b *[encodingSize1]byte) ringElement
ringDecodeAndDecompress1 decodes a 32-byte slice to a ring element where
each bit is mapped to 0 or ⌈q/2⌋.
It implements ByteDecode₁, according to FIPS 203, Algorithm 6, followed by
Decompress₁, according to FIPS 203, Definition 4.8.
func ringDecodeAndDecompress10(bb *[encodingSize10]byte) ringElement
ringDecodeAndDecompress10 decodes a 320-byte encoding of a ring element
where each ten bits are mapped to an equidistant distribution.
It implements ByteDecode₁₀, according to FIPS 203, Algorithm 6, followed by
Decompress₁₀, according to FIPS 203, Definition 4.8.
func ringDecodeAndDecompress11(bb *[encodingSize11]byte) ringElement
ringDecodeAndDecompress11 decodes a 352-byte encoding of a ring element
where each eleven bits are mapped to an equidistant distribution.
It implements ByteDecode₁₁, according to FIPS 203, Algorithm 6, followed by
Decompress₁₁, according to FIPS 203, Definition 4.8.
func ringDecodeAndDecompress4(b *[encodingSize4]byte) ringElement
ringDecodeAndDecompress4 decodes a 128-byte encoding of a ring element where
each four bits are mapped to an equidistant distribution.
It implements ByteDecode₄, according to FIPS 203, Algorithm 6, followed by
Decompress₄, according to FIPS 203, Definition 4.8.
func ringDecodeAndDecompress5(bb *[encodingSize5]byte) ringElement
ringDecodeAndDecompress5 decodes a 160-byte encoding of a ring element where
each five bits are mapped to an equidistant distribution.
It implements ByteDecode₅, according to FIPS 203, Algorithm 6, followed by
Decompress₅, according to FIPS 203, Definition 4.8.
func samplePolyCBD(s []byte, b byte) ringElement
samplePolyCBD draws a ringElement from the special Dη distribution given a
stream of random bytes generated by the PRF function, according to FIPS 203,
Algorithm 8 and Definition 4.3.
crypto/internal/fips140/nistec
func P256OrdInverse(k []byte) ([]byte, error)
func boothW5(in uint) (int, int)
func boothW6(in uint) (int, int)
func bytesToLimbs(l *[4]uint64, b *[32]byte)
func init()
func limbsToBytes(b *[32]byte, l *[4]uint64)
func p224B() *fiat.P224Element
func p224CheckOnCurve(x, y *fiat.P224Element) error
func p224Polynomial(y2, x *fiat.P224Element) *fiat.P224Element
p224Polynomial sets y2 to x³ - 3x + b, and returns y2.
func p224Sqrt(e, x *fiat.P224Element) (isSquare bool)
p224Sqrt sets e to a square root of x. If x is not a square, p224Sqrt
returns false and e is unchanged. e and x can overlap.
func p224SqrtCandidate(r, x *fiat.P224Element)
p224SqrtCandidate sets r to a square root candidate for x. r and x must not
overlap.
func p256Add(res, x, y *p256Element)
p256Add sets res = x + y.
func p256BigToLittle(l *p256Element, b *[32]byte)
func p256CheckOnCurve(x, y *p256Element) error
func p256Equal(a, b *p256Element) int
p256Equal returns 1 if a and b are equal and 0 otherwise.
func p256FromMont(res, in *p256Element)
Montgomery multiplication by R⁻¹, or 1 outside the domain. Sets res = in *
R⁻¹, bringing res out of the Montgomery domain.
func p256Inverse(out, in *p256Element)
p256Inverse sets out to in⁻¹ mod p. If in is zero, out will be zero.
func p256LessThanP(x *p256Element) int
p256LessThanP returns 1 if x < p, and 0 otherwise. Note that a p256Element
is not allowed to be equal to or greater than p, so if this function returns
0 then x is invalid.
func p256LittleToBig(b *[32]byte, l *p256Element)
func p256MovCond(res, a, b *P256Point, cond int)
If cond is 0, sets res = b, otherwise sets res = a.
func p256Mul(res, in1, in2 *p256Element)
Montgomery multiplication. Sets res = in1 * in2 * R⁻¹ mod p.
func p256NegCond(val *p256Element, cond int)
If cond is not 0, sets val = -val mod p.
func p256OrdBigToLittle(l *p256OrdElement, b *[32]byte)
func p256OrdLittleToBig(b *[32]byte, l *p256OrdElement)
func p256OrdMul(res, in1, in2 *p256OrdElement)
Montgomery multiplication modulo org(G). Sets res = in1 * in2 * R⁻¹.
func p256OrdReduce(s *p256OrdElement)
p256OrdReduce ensures s is in the range [0, ord(G)-1].
func p256OrdSqr(res, in *p256OrdElement, n int)
Montgomery square modulo org(G), repeated n times (n >= 1).
func p256PointAddAffineAsm(res, in1 *P256Point, in2 *p256AffinePoint, sign, sel, zero int)
Point addition with an affine point and constant time conditions.
If zero is 0, sets res = in2. If sel is 0, sets res = in1. If sign is not 0,
sets res = in1 + -in2. Otherwise, sets res = in1 + in2
func p256PointAddAsm(res, in1, in2 *P256Point) int
Point addition. Sets res = in1 + in2. Returns one if the two input points
were equal and zero otherwise. If in1 or in2 are the point at infinity,
res and the return value are undefined.
func p256PointDoubleAsm(res, in *P256Point)
Point doubling. Sets res = in + in. in can be the point at infinity.
func p256Select(res *P256Point, table *p256Table, idx int)
p256Select sets res to the point at index idx in the table. idx must be in
[0, 15]. It executes in constant time.
func p256SelectAffine(res *p256AffinePoint, table *p256AffineTable, idx int)
p256SelectAffine sets res to the point at index idx in the table. idx must
be in [0, 31]. It executes in constant time.
func p256Sqr(res, in *p256Element, n int)
Montgomery square, repeated n times (n >= 1).
func p256Sqrt(e, x *p256Element) (isSquare bool)
p256Sqrt sets e to a square root of x. If x is not a square, p256Sqrt
returns false and e is unchanged. e and x can overlap.
func p384B() *fiat.P384Element
func p384CheckOnCurve(x, y *fiat.P384Element) error
func p384Polynomial(y2, x *fiat.P384Element) *fiat.P384Element
p384Polynomial sets y2 to x³ - 3x + b, and returns y2.
func p384Sqrt(e, x *fiat.P384Element) (isSquare bool)
p384Sqrt sets e to a square root of x. If x is not a square, p384Sqrt
returns false and e is unchanged. e and x can overlap.
func p384SqrtCandidate(z, x *fiat.P384Element)
p384SqrtCandidate sets z to a square root candidate for x. z and x must not
overlap.
func p521B() *fiat.P521Element
func p521CheckOnCurve(x, y *fiat.P521Element) error
func p521Polynomial(y2, x *fiat.P521Element) *fiat.P521Element
p521Polynomial sets y2 to x³ - 3x + b, and returns y2.
func p521Sqrt(e, x *fiat.P521Element) (isSquare bool)
p521Sqrt sets e to a square root of x. If x is not a square, p521Sqrt
returns false and e is unchanged. e and x can overlap.
func p521SqrtCandidate(z, x *fiat.P521Element)
p521SqrtCandidate sets z to a square root candidate for x. z and x must not
overlap.
func uint64IsZero(x uint64) int
uint64IsZero returns 1 if x is zero and zero otherwise.
TYPES
type P224Point struct {
x, y, z *fiat.P224Element
}
P224Point is a P224 point. The zero value is NOT valid.
func NewP224Point() *P224Point
NewP224Point returns a new P224Point representing the point at infinity
point.
func (q *P224Point) Add(p1, p2 *P224Point) *P224Point
Add sets q = p1 + p2, and returns q. The points may overlap.
func (p *P224Point) Bytes() []byte
Bytes returns the uncompressed or infinity encoding of p, as specified in
SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of the point at
infinity is shorter than all other encodings.
func (p *P224Point) BytesCompressed() []byte
BytesCompressed returns the compressed or infinity encoding of p,
as specified in SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of
the point at infinity is shorter than all other encodings.
func (p *P224Point) BytesX() ([]byte, error)
BytesX returns the encoding of the x-coordinate of p, as specified in SEC 1,
Version 2.0, Section 2.3.5, or an error if p is the point at infinity.
func (q *P224Point) Double(p *P224Point) *P224Point
Double sets q = p + p, and returns q. The points may overlap.
func (p *P224Point) ScalarBaseMult(scalar []byte) (*P224Point, error)
ScalarBaseMult sets p = scalar * B, where B is the canonical generator,
and returns p.
func (p *P224Point) ScalarMult(q *P224Point, scalar []byte) (*P224Point, error)
ScalarMult sets p = scalar * q, and returns p.
func (q *P224Point) Select(p1, p2 *P224Point, cond int) *P224Point
Select sets q to p1 if cond == 1, and to p2 if cond == 0.
func (p *P224Point) Set(q *P224Point) *P224Point
Set sets p = q and returns p.
func (p *P224Point) SetBytes(b []byte) (*P224Point, error)
SetBytes sets p to the compressed, uncompressed, or infinity value encoded
in b, as specified in SEC 1, Version 2.0, Section 2.3.4. If the point is not
on the curve, it returns nil and an error, and the receiver is unchanged.
Otherwise, it returns p.
func (p *P224Point) SetGenerator() *P224Point
SetGenerator sets p to the canonical generator and returns p.
func (p *P224Point) bytes(out *[1 + 2*p224ElementLength]byte) []byte
func (p *P224Point) bytesCompressed(out *[1 + p224ElementLength]byte) []byte
func (p *P224Point) bytesX(out *[p224ElementLength]byte) ([]byte, error)
func (p *P224Point) generatorTable() *[p224ElementLength * 2]p224Table
generatorTable returns a sequence of p224Tables. The first table contains
multiples of G. Each successive table is the previous table doubled four
times.
type P256Point struct {
x, y, z p256Element
}
P256Point is a P-256 point. The zero value should not be assumed to be valid
(although it is in this implementation).
func NewP256Point() *P256Point
NewP256Point returns a new P256Point representing the point at infinity.
func (q *P256Point) Add(r1, r2 *P256Point) *P256Point
Add sets q = p1 + p2, and returns q. The points may overlap.
func (p *P256Point) Bytes() []byte
Bytes returns the uncompressed or infinity encoding of p, as specified in
SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of the point at
infinity is shorter than all other encodings.
func (p *P256Point) BytesCompressed() []byte
BytesCompressed returns the compressed or infinity encoding of p,
as specified in SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of
the point at infinity is shorter than all other encodings.
func (p *P256Point) BytesX() ([]byte, error)
BytesX returns the encoding of the x-coordinate of p, as specified in SEC 1,
Version 2.0, Section 2.3.5, or an error if p is the point at infinity.
func (q *P256Point) Double(p *P256Point) *P256Point
Double sets q = p + p, and returns q. The points may overlap.
func (r *P256Point) ScalarBaseMult(scalar []byte) (*P256Point, error)
ScalarBaseMult sets r = scalar * generator, where scalar is a 32-byte big
endian value, and returns r. If scalar is not 32 bytes long, ScalarBaseMult
returns an error and the receiver is unchanged.
func (r *P256Point) ScalarMult(q *P256Point, scalar []byte) (*P256Point, error)
ScalarMult sets r = scalar * q, where scalar is a 32-byte big endian value,
and returns r. If scalar is not 32 bytes long, ScalarBaseMult returns an
error and the receiver is unchanged.
func (q *P256Point) Select(p1, p2 *P256Point, cond int) *P256Point
Select sets q to p1 if cond == 1, and to p2 if cond == 0.
func (p *P256Point) Set(q *P256Point) *P256Point
Set sets p = q and returns p.
func (p *P256Point) SetBytes(b []byte) (*P256Point, error)
SetBytes sets p to the compressed, uncompressed, or infinity value encoded
in b, as specified in SEC 1, Version 2.0, Section 2.3.4. If the point is not
on the curve, it returns nil and an error, and the receiver is unchanged.
Otherwise, it returns p.
func (p *P256Point) SetGenerator() *P256Point
SetGenerator sets p to the canonical generator and returns p.
func (p *P256Point) affineFromMont(x, y *p256Element)
affineFromMont sets (x, y) to the affine coordinates of p, converted out of
the Montgomery domain.
func (p *P256Point) bytes(out *[p256UncompressedLength]byte) []byte
func (p *P256Point) bytesCompressed(out *[p256CompressedLength]byte) []byte
func (p *P256Point) bytesX(out *[p256ElementLength]byte) ([]byte, error)
func (p *P256Point) isInfinity() int
isInfinity returns 1 if p is the point at infinity and 0 otherwise.
func (p *P256Point) p256BaseMult(scalar *p256OrdElement)
func (p *P256Point) p256ScalarMult(scalar *p256OrdElement)
type P384Point struct {
x, y, z *fiat.P384Element
}
P384Point is a P384 point. The zero value is NOT valid.
func NewP384Point() *P384Point
NewP384Point returns a new P384Point representing the point at infinity
point.
func (q *P384Point) Add(p1, p2 *P384Point) *P384Point
Add sets q = p1 + p2, and returns q. The points may overlap.
func (p *P384Point) Bytes() []byte
Bytes returns the uncompressed or infinity encoding of p, as specified in
SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of the point at
infinity is shorter than all other encodings.
func (p *P384Point) BytesCompressed() []byte
BytesCompressed returns the compressed or infinity encoding of p,
as specified in SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of
the point at infinity is shorter than all other encodings.
func (p *P384Point) BytesX() ([]byte, error)
BytesX returns the encoding of the x-coordinate of p, as specified in SEC 1,
Version 2.0, Section 2.3.5, or an error if p is the point at infinity.
func (q *P384Point) Double(p *P384Point) *P384Point
Double sets q = p + p, and returns q. The points may overlap.
func (p *P384Point) ScalarBaseMult(scalar []byte) (*P384Point, error)
ScalarBaseMult sets p = scalar * B, where B is the canonical generator,
and returns p.
func (p *P384Point) ScalarMult(q *P384Point, scalar []byte) (*P384Point, error)
ScalarMult sets p = scalar * q, and returns p.
func (q *P384Point) Select(p1, p2 *P384Point, cond int) *P384Point
Select sets q to p1 if cond == 1, and to p2 if cond == 0.
func (p *P384Point) Set(q *P384Point) *P384Point
Set sets p = q and returns p.
func (p *P384Point) SetBytes(b []byte) (*P384Point, error)
SetBytes sets p to the compressed, uncompressed, or infinity value encoded
in b, as specified in SEC 1, Version 2.0, Section 2.3.4. If the point is not
on the curve, it returns nil and an error, and the receiver is unchanged.
Otherwise, it returns p.
func (p *P384Point) SetGenerator() *P384Point
SetGenerator sets p to the canonical generator and returns p.
func (p *P384Point) bytes(out *[1 + 2*p384ElementLength]byte) []byte
func (p *P384Point) bytesCompressed(out *[1 + p384ElementLength]byte) []byte
func (p *P384Point) bytesX(out *[p384ElementLength]byte) ([]byte, error)
func (p *P384Point) generatorTable() *[p384ElementLength * 2]p384Table
generatorTable returns a sequence of p384Tables. The first table contains
multiples of G. Each successive table is the previous table doubled four
times.
type P521Point struct {
x, y, z *fiat.P521Element
}
P521Point is a P521 point. The zero value is NOT valid.
func NewP521Point() *P521Point
NewP521Point returns a new P521Point representing the point at infinity
point.
func (q *P521Point) Add(p1, p2 *P521Point) *P521Point
Add sets q = p1 + p2, and returns q. The points may overlap.
func (p *P521Point) Bytes() []byte
Bytes returns the uncompressed or infinity encoding of p, as specified in
SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of the point at
infinity is shorter than all other encodings.
func (p *P521Point) BytesCompressed() []byte
BytesCompressed returns the compressed or infinity encoding of p,
as specified in SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of
the point at infinity is shorter than all other encodings.
func (p *P521Point) BytesX() ([]byte, error)
BytesX returns the encoding of the x-coordinate of p, as specified in SEC 1,
Version 2.0, Section 2.3.5, or an error if p is the point at infinity.
func (q *P521Point) Double(p *P521Point) *P521Point
Double sets q = p + p, and returns q. The points may overlap.
func (p *P521Point) ScalarBaseMult(scalar []byte) (*P521Point, error)
ScalarBaseMult sets p = scalar * B, where B is the canonical generator,
and returns p.
func (p *P521Point) ScalarMult(q *P521Point, scalar []byte) (*P521Point, error)
ScalarMult sets p = scalar * q, and returns p.
func (q *P521Point) Select(p1, p2 *P521Point, cond int) *P521Point
Select sets q to p1 if cond == 1, and to p2 if cond == 0.
func (p *P521Point) Set(q *P521Point) *P521Point
Set sets p = q and returns p.
func (p *P521Point) SetBytes(b []byte) (*P521Point, error)
SetBytes sets p to the compressed, uncompressed, or infinity value encoded
in b, as specified in SEC 1, Version 2.0, Section 2.3.4. If the point is not
on the curve, it returns nil and an error, and the receiver is unchanged.
Otherwise, it returns p.
func (p *P521Point) SetGenerator() *P521Point
SetGenerator sets p to the canonical generator and returns p.
func (p *P521Point) bytes(out *[1 + 2*p521ElementLength]byte) []byte
func (p *P521Point) bytesCompressed(out *[1 + p521ElementLength]byte) []byte
func (p *P521Point) bytesX(out *[p521ElementLength]byte) ([]byte, error)
func (p *P521Point) generatorTable() *[p521ElementLength * 2]p521Table
generatorTable returns a sequence of p521Tables. The first table contains
multiples of G. Each successive table is the previous table doubled four
times.
type p224Table [15]*P224Point
A p224Table holds the first 15 multiples of a point at offset -1, so [1]P
is at table[0], [15]P is at table[14], and [0]P is implicitly the identity
point.
func (table *p224Table) Select(p *P224Point, n uint8)
Select selects the n-th multiple of the table base point into p. It works in
constant time by iterating over every entry of the table. n must be in [0,
15].
type p256AffinePoint struct {
x, y p256Element
}
p256AffinePoint is a point in affine coordinates (x, y). x and y are still
Montgomery domain elements. The point can't be the point at infinity.
type p256AffineTable [32]p256AffinePoint
p256AffineTable is a table of the first 32 multiples of a point. Points are
stored at an index offset of -1 like in p256Table, and [0]P is not stored.
type p256Element [4]uint64
p256Element is a P-256 base field element in [0, P-1] in the Montgomery
domain (with R 2²⁵⁶) as four limbs in little-endian order value.
func p256Polynomial(y2, x *p256Element) *p256Element
p256Polynomial sets y2 to x³ - 3x + b, and returns y2.
type p256OrdElement [4]uint64
p256OrdElement is a P-256 scalar field element in [0, ord(G)-1] in the
Montgomery domain (with R 2²⁵⁶) as four uint64 limbs in little-endian order.
type p256Table [16]P256Point
p256Table is a table of the first 16 multiples of a point. Points are stored
at an index offset of -1 so [8]P is at index 7, P is at 0, and [16]P is at
15. [0]P is the point at infinity and it's not stored.
type p384Table [15]*P384Point
A p384Table holds the first 15 multiples of a point at offset -1, so [1]P
is at table[0], [15]P is at table[14], and [0]P is implicitly the identity
point.
func (table *p384Table) Select(p *P384Point, n uint8)
Select selects the n-th multiple of the table base point into p. It works in
constant time by iterating over every entry of the table. n must be in [0,
15].
type p521Table [15]*P521Point
A p521Table holds the first 15 multiples of a point at offset -1, so [1]P
is at table[0], [15]P is at table[14], and [0]P is implicitly the identity
point.
func (table *p521Table) Select(p *P521Point, n uint8)
Select selects the n-th multiple of the table base point into p. It works in
constant time by iterating over every entry of the table. n must be in [0,
15].
crypto/internal/fips140/nistec/fiat
func p224Add(out1 *p224MontgomeryDomainFieldElement, arg1 *p224MontgomeryDomainFieldElement, arg2 *p224MontgomeryDomainFieldElement)
p224Add adds two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p224CmovznzU64(out1 *uint64, arg1 p224Uint1, arg2 uint64, arg3 uint64)
p224CmovznzU64 is a single-word conditional move.
Postconditions:
out1 = (if arg1 = 0 then arg2 else arg3)
Input Bounds:
arg1: [0x0 ~> 0x1]
arg2: [0x0 ~> 0xffffffffffffffff]
arg3: [0x0 ~> 0xffffffffffffffff]
Output Bounds:
out1: [0x0 ~> 0xffffffffffffffff]
func p224FromBytes(out1 *[4]uint64, arg1 *[28]uint8)
p224FromBytes deserializes a field element NOT in the Montgomery domain from
bytes in little-endian order.
Preconditions:
0 ≤ bytes_eval arg1 < m
Postconditions:
eval out1 mod m = bytes_eval arg1 mod m
0 ≤ eval out1 < m
Input Bounds:
arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
Output Bounds:
out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffff]]
func p224FromMontgomery(out1 *p224NonMontgomeryDomainFieldElement, arg1 *p224MontgomeryDomainFieldElement)
p224FromMontgomery translates a field element out of the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m
0 ≤ eval out1 < m
func p224InvertEndianness(v []byte)
func p224Mul(out1 *p224MontgomeryDomainFieldElement, arg1 *p224MontgomeryDomainFieldElement, arg2 *p224MontgomeryDomainFieldElement)
p224Mul multiplies two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p224Selectznz(out1 *[4]uint64, arg1 p224Uint1, arg2 *[4]uint64, arg3 *[4]uint64)
p224Selectznz is a multi-limb conditional select.
Postconditions:
eval out1 = (if arg1 = 0 then eval arg2 else eval arg3)
Input Bounds:
arg1: [0x0 ~> 0x1]
arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
Output Bounds:
out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
func p224SetOne(out1 *p224MontgomeryDomainFieldElement)
p224SetOne returns the field element one in the Montgomery domain.
Postconditions:
eval (from_montgomery out1) mod m = 1 mod m
0 ≤ eval out1 < m
func p224Square(out1 *p224MontgomeryDomainFieldElement, arg1 *p224MontgomeryDomainFieldElement)
p224Square squares a field element in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m
0 ≤ eval out1 < m
func p224Sub(out1 *p224MontgomeryDomainFieldElement, arg1 *p224MontgomeryDomainFieldElement, arg2 *p224MontgomeryDomainFieldElement)
p224Sub subtracts two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p224ToBytes(out1 *[28]uint8, arg1 *[4]uint64)
p224ToBytes serializes a field element NOT in the Montgomery domain to bytes
in little-endian order.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..27]
Input Bounds:
arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffff]]
Output Bounds:
out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
func p224ToMontgomery(out1 *p224MontgomeryDomainFieldElement, arg1 *p224NonMontgomeryDomainFieldElement)
p224ToMontgomery translates a field element into the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = eval arg1 mod m
0 ≤ eval out1 < m
func p256Add(out1 *p256MontgomeryDomainFieldElement, arg1 *p256MontgomeryDomainFieldElement, arg2 *p256MontgomeryDomainFieldElement)
p256Add adds two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p256CmovznzU64(out1 *uint64, arg1 p256Uint1, arg2 uint64, arg3 uint64)
p256CmovznzU64 is a single-word conditional move.
Postconditions:
out1 = (if arg1 = 0 then arg2 else arg3)
Input Bounds:
arg1: [0x0 ~> 0x1]
arg2: [0x0 ~> 0xffffffffffffffff]
arg3: [0x0 ~> 0xffffffffffffffff]
Output Bounds:
out1: [0x0 ~> 0xffffffffffffffff]
func p256FromBytes(out1 *[4]uint64, arg1 *[32]uint8)
p256FromBytes deserializes a field element NOT in the Montgomery domain from
bytes in little-endian order.
Preconditions:
0 ≤ bytes_eval arg1 < m
Postconditions:
eval out1 mod m = bytes_eval arg1 mod m
0 ≤ eval out1 < m
Input Bounds:
arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
Output Bounds:
out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
func p256FromMontgomery(out1 *p256NonMontgomeryDomainFieldElement, arg1 *p256MontgomeryDomainFieldElement)
p256FromMontgomery translates a field element out of the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^4) mod m
0 ≤ eval out1 < m
func p256InvertEndianness(v []byte)
func p256Mul(out1 *p256MontgomeryDomainFieldElement, arg1 *p256MontgomeryDomainFieldElement, arg2 *p256MontgomeryDomainFieldElement)
p256Mul multiplies two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p256Selectznz(out1 *[4]uint64, arg1 p256Uint1, arg2 *[4]uint64, arg3 *[4]uint64)
p256Selectznz is a multi-limb conditional select.
Postconditions:
eval out1 = (if arg1 = 0 then eval arg2 else eval arg3)
Input Bounds:
arg1: [0x0 ~> 0x1]
arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
Output Bounds:
out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
func p256SetOne(out1 *p256MontgomeryDomainFieldElement)
p256SetOne returns the field element one in the Montgomery domain.
Postconditions:
eval (from_montgomery out1) mod m = 1 mod m
0 ≤ eval out1 < m
func p256Square(out1 *p256MontgomeryDomainFieldElement, arg1 *p256MontgomeryDomainFieldElement)
p256Square squares a field element in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m
0 ≤ eval out1 < m
func p256Sub(out1 *p256MontgomeryDomainFieldElement, arg1 *p256MontgomeryDomainFieldElement, arg2 *p256MontgomeryDomainFieldElement)
p256Sub subtracts two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p256ToBytes(out1 *[32]uint8, arg1 *[4]uint64)
p256ToBytes serializes a field element NOT in the Montgomery domain to bytes
in little-endian order.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31]
Input Bounds:
arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
Output Bounds:
out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
func p256ToMontgomery(out1 *p256MontgomeryDomainFieldElement, arg1 *p256NonMontgomeryDomainFieldElement)
p256ToMontgomery translates a field element into the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = eval arg1 mod m
0 ≤ eval out1 < m
func p384Add(out1 *p384MontgomeryDomainFieldElement, arg1 *p384MontgomeryDomainFieldElement, arg2 *p384MontgomeryDomainFieldElement)
p384Add adds two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p384CmovznzU64(out1 *uint64, arg1 p384Uint1, arg2 uint64, arg3 uint64)
p384CmovznzU64 is a single-word conditional move.
Postconditions:
out1 = (if arg1 = 0 then arg2 else arg3)
Input Bounds:
arg1: [0x0 ~> 0x1]
arg2: [0x0 ~> 0xffffffffffffffff]
arg3: [0x0 ~> 0xffffffffffffffff]
Output Bounds:
out1: [0x0 ~> 0xffffffffffffffff]
func p384FromBytes(out1 *[6]uint64, arg1 *[48]uint8)
p384FromBytes deserializes a field element NOT in the Montgomery domain from
bytes in little-endian order.
Preconditions:
0 ≤ bytes_eval arg1 < m
Postconditions:
eval out1 mod m = bytes_eval arg1 mod m
0 ≤ eval out1 < m
Input Bounds:
arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
Output Bounds:
out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
func p384FromMontgomery(out1 *p384NonMontgomeryDomainFieldElement, arg1 *p384MontgomeryDomainFieldElement)
p384FromMontgomery translates a field element out of the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^6) mod m
0 ≤ eval out1 < m
func p384InvertEndianness(v []byte)
func p384Mul(out1 *p384MontgomeryDomainFieldElement, arg1 *p384MontgomeryDomainFieldElement, arg2 *p384MontgomeryDomainFieldElement)
p384Mul multiplies two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p384Selectznz(out1 *[6]uint64, arg1 p384Uint1, arg2 *[6]uint64, arg3 *[6]uint64)
p384Selectznz is a multi-limb conditional select.
Postconditions:
eval out1 = (if arg1 = 0 then eval arg2 else eval arg3)
Input Bounds:
arg1: [0x0 ~> 0x1]
arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
Output Bounds:
out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
func p384SetOne(out1 *p384MontgomeryDomainFieldElement)
p384SetOne returns the field element one in the Montgomery domain.
Postconditions:
eval (from_montgomery out1) mod m = 1 mod m
0 ≤ eval out1 < m
func p384Square(out1 *p384MontgomeryDomainFieldElement, arg1 *p384MontgomeryDomainFieldElement)
p384Square squares a field element in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m
0 ≤ eval out1 < m
func p384Sub(out1 *p384MontgomeryDomainFieldElement, arg1 *p384MontgomeryDomainFieldElement, arg2 *p384MontgomeryDomainFieldElement)
p384Sub subtracts two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p384ToBytes(out1 *[48]uint8, arg1 *[6]uint64)
p384ToBytes serializes a field element NOT in the Montgomery domain to bytes
in little-endian order.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..47]
Input Bounds:
arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
Output Bounds:
out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff]]
func p384ToMontgomery(out1 *p384MontgomeryDomainFieldElement, arg1 *p384NonMontgomeryDomainFieldElement)
p384ToMontgomery translates a field element into the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = eval arg1 mod m
0 ≤ eval out1 < m
func p521Add(out1 *p521MontgomeryDomainFieldElement, arg1 *p521MontgomeryDomainFieldElement, arg2 *p521MontgomeryDomainFieldElement)
p521Add adds two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p521CmovznzU64(out1 *uint64, arg1 p521Uint1, arg2 uint64, arg3 uint64)
p521CmovznzU64 is a single-word conditional move.
Postconditions:
out1 = (if arg1 = 0 then arg2 else arg3)
Input Bounds:
arg1: [0x0 ~> 0x1]
arg2: [0x0 ~> 0xffffffffffffffff]
arg3: [0x0 ~> 0xffffffffffffffff]
Output Bounds:
out1: [0x0 ~> 0xffffffffffffffff]
func p521FromBytes(out1 *[9]uint64, arg1 *[66]uint8)
p521FromBytes deserializes a field element NOT in the Montgomery domain from
bytes in little-endian order.
Preconditions:
0 ≤ bytes_eval arg1 < m
Postconditions:
eval out1 mod m = bytes_eval arg1 mod m
0 ≤ eval out1 < m
Input Bounds:
arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x1]]
Output Bounds:
out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x1ff]]
func p521FromMontgomery(out1 *p521NonMontgomeryDomainFieldElement, arg1 *p521MontgomeryDomainFieldElement)
p521FromMontgomery translates a field element out of the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^9) mod m
0 ≤ eval out1 < m
func p521InvertEndianness(v []byte)
func p521Mul(out1 *p521MontgomeryDomainFieldElement, arg1 *p521MontgomeryDomainFieldElement, arg2 *p521MontgomeryDomainFieldElement)
p521Mul multiplies two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p521Selectznz(out1 *[9]uint64, arg1 p521Uint1, arg2 *[9]uint64, arg3 *[9]uint64)
p521Selectznz is a multi-limb conditional select.
Postconditions:
eval out1 = (if arg1 = 0 then eval arg2 else eval arg3)
Input Bounds:
arg1: [0x0 ~> 0x1]
arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
Output Bounds:
out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
func p521SetOne(out1 *p521MontgomeryDomainFieldElement)
p521SetOne returns the field element one in the Montgomery domain.
Postconditions:
eval (from_montgomery out1) mod m = 1 mod m
0 ≤ eval out1 < m
func p521Square(out1 *p521MontgomeryDomainFieldElement, arg1 *p521MontgomeryDomainFieldElement)
p521Square squares a field element in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m
0 ≤ eval out1 < m
func p521Sub(out1 *p521MontgomeryDomainFieldElement, arg1 *p521MontgomeryDomainFieldElement, arg2 *p521MontgomeryDomainFieldElement)
p521Sub subtracts two field elements in the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
0 ≤ eval arg2 < m
Postconditions:
eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m
0 ≤ eval out1 < m
func p521ToBytes(out1 *[66]uint8, arg1 *[9]uint64)
p521ToBytes serializes a field element NOT in the Montgomery domain to bytes
in little-endian order.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..65]
Input Bounds:
arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x1ff]]
Output Bounds:
out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x1]]
func p521ToMontgomery(out1 *p521MontgomeryDomainFieldElement, arg1 *p521NonMontgomeryDomainFieldElement)
p521ToMontgomery translates a field element into the Montgomery domain.
Preconditions:
0 ≤ eval arg1 < m
Postconditions:
eval (from_montgomery out1) mod m = eval arg1 mod m
0 ≤ eval out1 < m
TYPES
type P224Element struct {
x p224MontgomeryDomainFieldElement
}
P224Element is an integer modulo 2^224 - 2^96 + 1.
The zero value is a valid zero element.
func (e *P224Element) Add(t1, t2 *P224Element) *P224Element
Add sets e = t1 + t2, and returns e.
func (e *P224Element) Bytes() []byte
Bytes returns the 28-byte big-endian encoding of e.
func (e *P224Element) Equal(t *P224Element) int
Equal returns 1 if e == t, and zero otherwise.
func (e *P224Element) Invert(x *P224Element) *P224Element
Invert sets e = 1/x, and returns e.
If x == 0, Invert returns e = 0.
func (e *P224Element) IsZero() int
IsZero returns 1 if e == 0, and zero otherwise.
func (e *P224Element) Mul(t1, t2 *P224Element) *P224Element
Mul sets e = t1 * t2, and returns e.
func (e *P224Element) One() *P224Element
One sets e = 1, and returns e.
func (v *P224Element) Select(a, b *P224Element, cond int) *P224Element
Select sets v to a if cond == 1, and to b if cond == 0.
func (e *P224Element) Set(t *P224Element) *P224Element
Set sets e = t, and returns e.
func (e *P224Element) SetBytes(v []byte) (*P224Element, error)
SetBytes sets e = v, where v is a big-endian 28-byte encoding, and returns
e. If v is not 28 bytes or it encodes a value higher than 2^224 - 2^96 + 1,
SetBytes returns nil and an error, and e is unchanged.
func (e *P224Element) Square(t *P224Element) *P224Element
Square sets e = t * t, and returns e.
func (e *P224Element) Sub(t1, t2 *P224Element) *P224Element
Sub sets e = t1 - t2, and returns e.
func (e *P224Element) bytes(out *[p224ElementLen]byte) []byte
type P256Element struct {
x p256MontgomeryDomainFieldElement
}
P256Element is an integer modulo 2^256 - 2^224 + 2^192 + 2^96 - 1.
The zero value is a valid zero element.
func (e *P256Element) Add(t1, t2 *P256Element) *P256Element
Add sets e = t1 + t2, and returns e.
func (e *P256Element) Bytes() []byte
Bytes returns the 32-byte big-endian encoding of e.
func (e *P256Element) Equal(t *P256Element) int
Equal returns 1 if e == t, and zero otherwise.
func (e *P256Element) Invert(x *P256Element) *P256Element
Invert sets e = 1/x, and returns e.
If x == 0, Invert returns e = 0.
func (e *P256Element) IsZero() int
IsZero returns 1 if e == 0, and zero otherwise.
func (e *P256Element) Mul(t1, t2 *P256Element) *P256Element
Mul sets e = t1 * t2, and returns e.
func (e *P256Element) One() *P256Element
One sets e = 1, and returns e.
func (v *P256Element) Select(a, b *P256Element, cond int) *P256Element
Select sets v to a if cond == 1, and to b if cond == 0.
func (e *P256Element) Set(t *P256Element) *P256Element
Set sets e = t, and returns e.
func (e *P256Element) SetBytes(v []byte) (*P256Element, error)
SetBytes sets e = v, where v is a big-endian 32-byte encoding, and returns
e. If v is not 32 bytes or it encodes a value higher than 2^256 - 2^224 +
2^192 + 2^96 - 1, SetBytes returns nil and an error, and e is unchanged.
func (e *P256Element) Square(t *P256Element) *P256Element
Square sets e = t * t, and returns e.
func (e *P256Element) Sub(t1, t2 *P256Element) *P256Element
Sub sets e = t1 - t2, and returns e.
func (e *P256Element) bytes(out *[p256ElementLen]byte) []byte
type P384Element struct {
x p384MontgomeryDomainFieldElement
}
P384Element is an integer modulo 2^384 - 2^128 - 2^96 + 2^32 - 1.
The zero value is a valid zero element.
func (e *P384Element) Add(t1, t2 *P384Element) *P384Element
Add sets e = t1 + t2, and returns e.
func (e *P384Element) Bytes() []byte
Bytes returns the 48-byte big-endian encoding of e.
func (e *P384Element) Equal(t *P384Element) int
Equal returns 1 if e == t, and zero otherwise.
func (e *P384Element) Invert(x *P384Element) *P384Element
Invert sets e = 1/x, and returns e.
If x == 0, Invert returns e = 0.
func (e *P384Element) IsZero() int
IsZero returns 1 if e == 0, and zero otherwise.
func (e *P384Element) Mul(t1, t2 *P384Element) *P384Element
Mul sets e = t1 * t2, and returns e.
func (e *P384Element) One() *P384Element
One sets e = 1, and returns e.
func (v *P384Element) Select(a, b *P384Element, cond int) *P384Element
Select sets v to a if cond == 1, and to b if cond == 0.
func (e *P384Element) Set(t *P384Element) *P384Element
Set sets e = t, and returns e.
func (e *P384Element) SetBytes(v []byte) (*P384Element, error)
SetBytes sets e = v, where v is a big-endian 48-byte encoding, and returns
e. If v is not 48 bytes or it encodes a value higher than 2^384 - 2^128 -
2^96 + 2^32 - 1, SetBytes returns nil and an error, and e is unchanged.
func (e *P384Element) Square(t *P384Element) *P384Element
Square sets e = t * t, and returns e.
func (e *P384Element) Sub(t1, t2 *P384Element) *P384Element
Sub sets e = t1 - t2, and returns e.
func (e *P384Element) bytes(out *[p384ElementLen]byte) []byte
type P521Element struct {
x p521MontgomeryDomainFieldElement
}
P521Element is an integer modulo 2^521 - 1.
The zero value is a valid zero element.
func (e *P521Element) Add(t1, t2 *P521Element) *P521Element
Add sets e = t1 + t2, and returns e.
func (e *P521Element) Bytes() []byte
Bytes returns the 66-byte big-endian encoding of e.
func (e *P521Element) Equal(t *P521Element) int
Equal returns 1 if e == t, and zero otherwise.
func (e *P521Element) Invert(x *P521Element) *P521Element
Invert sets e = 1/x, and returns e.
If x == 0, Invert returns e = 0.
func (e *P521Element) IsZero() int
IsZero returns 1 if e == 0, and zero otherwise.
func (e *P521Element) Mul(t1, t2 *P521Element) *P521Element
Mul sets e = t1 * t2, and returns e.
func (e *P521Element) One() *P521Element
One sets e = 1, and returns e.
func (v *P521Element) Select(a, b *P521Element, cond int) *P521Element
Select sets v to a if cond == 1, and to b if cond == 0.
func (e *P521Element) Set(t *P521Element) *P521Element
Set sets e = t, and returns e.
func (e *P521Element) SetBytes(v []byte) (*P521Element, error)
SetBytes sets e = v, where v is a big-endian 66-byte encoding, and returns
e. If v is not 66 bytes or it encodes a value higher than 2^521 - 1,
SetBytes returns nil and an error, and e is unchanged.
func (e *P521Element) Square(t *P521Element) *P521Element
Square sets e = t * t, and returns e.
func (e *P521Element) Sub(t1, t2 *P521Element) *P521Element
Sub sets e = t1 - t2, and returns e.
func (e *P521Element) bytes(out *[p521ElementLen]byte) []byte
type p224MontgomeryDomainFieldElement [4]uint64
The type p224MontgomeryDomainFieldElement is a field element in the
Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
type p224NonMontgomeryDomainFieldElement [4]uint64
The type p224NonMontgomeryDomainFieldElement is a field element NOT in the
Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
type p224UntypedFieldElement = [4]uint64
type p256MontgomeryDomainFieldElement [4]uint64
The type p256MontgomeryDomainFieldElement is a field element in the
Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
type p256NonMontgomeryDomainFieldElement [4]uint64
The type p256NonMontgomeryDomainFieldElement is a field element NOT in the
Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
type p256UntypedFieldElement = [4]uint64
type p384MontgomeryDomainFieldElement [6]uint64
The type p384MontgomeryDomainFieldElement is a field element in the
Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff],
[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
type p384NonMontgomeryDomainFieldElement [6]uint64
The type p384NonMontgomeryDomainFieldElement is a field element NOT in the
Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff],
[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]]
type p384UntypedFieldElement = [6]uint64
type p521MontgomeryDomainFieldElement [9]uint64
The type p521MontgomeryDomainFieldElement is a field element in the
Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff],
[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff],
[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff],
[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff]]
type p521NonMontgomeryDomainFieldElement [9]uint64
The type p521NonMontgomeryDomainFieldElement is a field element NOT in the
Montgomery domain.
Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff],
[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff],
[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff],
[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~>
0xffffffffffffffff]]
type p521UntypedFieldElement = [9]uint64
crypto/internal/fips140/pbkdf2
func Key[Hash fips140.Hash](h func() Hash, password string, salt []byte, iter, keyLength int) ([]byte, error)
func init()
func setServiceIndicator(salt []byte, keyLength int)
crypto/internal/fips140/rsa
func DecryptOAEP(hash, mgfHash fips140.Hash, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error)
DecryptOAEP decrypts ciphertext using RSAES-OAEP.
func DecryptWithCheck(priv *PrivateKey, ciphertext []byte) ([]byte, error)
DecryptWithCheck performs the RSA private key operation and checks the
result to defend against errors in the CRT computation.
func DecryptWithoutCheck(priv *PrivateKey, ciphertext []byte) ([]byte, error)
DecryptWithoutCheck performs the RSA private key operation.
func Encrypt(pub *PublicKey, plaintext []byte) ([]byte, error)
Encrypt performs the RSA public key operation.
func EncryptOAEP(hash, mgfHash fips140.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)
EncryptOAEP encrypts the given message with RSAES-OAEP.
func PSSMaxSaltLength(pub *PublicKey, hash fips140.Hash) (int, error)
PSSMaxSaltLength returns the maximum salt length for a given public key and
hash function.
func SignPKCS1v15(priv *PrivateKey, hash string, hashed []byte) ([]byte, error)
SignPKCS1v15 calculates an RSASSA-PKCS1-v1.5 signature.
hash is the name of the hash function as returned by crypto.Hash.String or
the empty string to indicate that the message is signed directly.
func SignPSS(rand io.Reader, priv *PrivateKey, hash fips140.Hash, hashed []byte, saltLength int) ([]byte, error)
SignPSS calculates the signature of hashed using RSASSA-PSS.
func VerifyPKCS1v15(pub *PublicKey, hash string, hashed []byte, sig []byte) error
VerifyPKCS1v15 verifies an RSASSA-PKCS1-v1.5 signature.
hash is the name of the hash function as returned by crypto.Hash.String or
the empty string to indicate that the message is signed directly.
func VerifyPSS(pub *PublicKey, hash fips140.Hash, digest []byte, sig []byte) error
VerifyPSS verifies sig with RSASSA-PSS automatically detecting the salt
length.
func VerifyPSSWithSaltLength(pub *PublicKey, hash fips140.Hash, digest []byte, sig []byte, saltLength int) error
VerifyPSS verifies sig with RSASSA-PSS and an expected salt length.
func checkApprovedHash(hash fips140.Hash)
func checkApprovedHashName(hash string)
func checkPrivateKey(priv *PrivateKey) error
checkPrivateKey is called by the NewPrivateKey and GenerateKey functions,
and is allowed to modify priv.fipsApproved.
func checkPublicKey(pub *PublicKey) (fipsApproved bool, err error)
func decrypt(priv *PrivateKey, ciphertext []byte, check bool) ([]byte, error)
decrypt performs an RSA decryption of ciphertext into out. If check is true,
m^e is calculated and compared with ciphertext, in order to defend against
errors in the CRT computation.
func emsaPSSEncode(mHash []byte, emBits int, salt []byte, hash fips140.Hash) ([]byte, error)
func emsaPSSVerify(mHash, em []byte, emBits, sLen int, hash fips140.Hash) error
func encrypt(pub *PublicKey, plaintext []byte) ([]byte, error)
func incCounter(c *[4]byte)
incCounter increments a four byte, big-endian counter.
func isPrime(w []byte) bool
isPrime runs the Miller-Rabin Probabilistic Primality Test from FIPS 186-5,
Appendix B.3.1.
w must be a random odd integer greater than three in big-endian order.
isPrime might return false positives for adversarially chosen values.
isPrime is not constant-time.
func mgf1XOR(out []byte, hash fips140.Hash, seed []byte)
mgf1XOR XORs the bytes in out with a mask generated using the MGF1 function
specified in PKCS #1 v2.1.
func millerRabinIteration(mr *millerRabin, bb []byte) (bool, error)
func pkcs1v15ConstructEM(pub *PublicKey, hash string, hashed []byte) ([]byte, error)
func randomPrime(rand io.Reader, bits int) ([]byte, error)
randomPrime returns a random prime number of the given bit size following
the process in FIPS 186-5, Appendix A.1.3.
func signPKCS1v15(priv *PrivateKey, hash string, hashed []byte) ([]byte, error)
func verifyPKCS1v15(pub *PublicKey, hash string, hashed []byte, sig []byte) error
func verifyPSS(pub *PublicKey, hash fips140.Hash, digest []byte, sig []byte, saltLength int) error
TYPES
type PrivateKey struct {
pub PublicKey
d *bigmod.Nat
fipsApproved bool
}
func GenerateKey(rand io.Reader, bits int) (*PrivateKey, error)
GenerateKey generates a new RSA key pair of the given bit size. bits must be
at least 128.
func NewPrivateKey(N []byte, e int, d, P, Q []byte) (*PrivateKey, error)
NewPrivateKey creates a new RSA private key from the given parameters.
All values are in big-endian byte slice format, and may have leading zeros
or be shorter if leading zeroes were trimmed.
func NewPrivateKeyWithPrecomputation(N []byte, e int, d, P, Q, dP, dQ, qInv []byte) (*PrivateKey, error)
NewPrivateKeyWithPrecomputation creates a new RSA private key from the given
parameters, which include precomputed CRT values.
func NewPrivateKeyWithoutCRT(N []byte, e int, d []byte) (*PrivateKey, error)
NewPrivateKeyWithoutCRT creates a new RSA private key from the given
parameters.
This is meant for deprecated multi-prime keys, and is not FIPS 140
compliant.
func newPrivateKey(n *bigmod.Modulus, e int, d *bigmod.Nat, p, q *bigmod.Modulus) (*PrivateKey, error)
func testPrivateKey() *PrivateKey
func (priv *PrivateKey) Export() (N []byte, e int, d, P, Q, dP, dQ, qInv []byte)
Export returns the key parameters in big-endian byte slice format.
P, Q, dP, dQ, and qInv may be nil if the key was created with
NewPrivateKeyWithoutCRT.
func (priv *PrivateKey) PublicKey() *PublicKey
type PublicKey struct {
N *bigmod.Modulus
E int
}
func (pub *PublicKey) Size() int
Size returns the modulus size in bytes. Raw signatures and ciphertexts for
or by this public key will have the same size.
type millerRabin struct {
w *bigmod.Modulus
a uint
m []byte
}
func millerRabinSetup(w []byte) (*millerRabin, error)
millerRabinSetup prepares state that's reused across multiple iterations of
the Miller-Rabin test.
crypto/internal/fips140/sha256
func block(dig *Digest, p []byte)
func blockAMD64(dig *Digest, p []byte)
func blockAVX2(dig *Digest, p []byte)
func blockGeneric(dig *Digest, p []byte)
func blockSHANI(dig *Digest, p []byte)
func consumeUint32(b []byte) ([]byte, uint32)
func consumeUint64(b []byte) ([]byte, uint64)
func init()
TYPES
type Digest struct {
h [8]uint32
x [chunk]byte
nx int
len uint64
}
Digest is a SHA-224 or SHA-256 hash.Hash implementation.
func New() *Digest
New returns a new Digest computing the SHA-256 hash.
func New224() *Digest
New224 returns a new Digest computing the SHA-224 hash.
func (d *Digest) AppendBinary(b []byte) ([]byte, error)
func (d *Digest) BlockSize() int
func (d *Digest) MarshalBinary() ([]byte, error)
func (d *Digest) Reset()
func (d *Digest) Size() int
func (d *Digest) Sum(in []byte) []byte
func (d *Digest) UnmarshalBinary(b []byte) error
func (d *Digest) Write(p []byte) (nn int, err error)
func (d *Digest) checkSum() [size]byte
crypto/internal/fips140/sha3
func bytepad(data []byte, rate int) []byte
func init()
func keccakF1600(a *[200]byte)
func keccakF1600Generic(da *[200]byte)
keccakF1600Generic applies the Keccak permutation.
func leftEncode(x uint64) []byte
TYPES
type Digest struct {
n, rate int
dsbyte byte
}
func New224() *Digest
New224 returns a new Digest computing the SHA3-224 hash.
func New256() *Digest
New256 returns a new Digest computing the SHA3-256 hash.
func New384() *Digest
New384 returns a new Digest computing the SHA3-384 hash.
func New512() *Digest
New512 returns a new Digest computing the SHA3-512 hash.
func NewLegacyKeccak256() *Digest
NewLegacyKeccak256 returns a new Digest computing the legacy, non-standard
Keccak-256 hash.
func NewLegacyKeccak512() *Digest
NewLegacyKeccak512 returns a new Digest computing the legacy, non-standard
Keccak-512 hash.
func (d *Digest) AppendBinary(b []byte) ([]byte, error)
func (d *Digest) BlockSize() int
BlockSize returns the rate of sponge underlying this hash function.
func (d *Digest) Clone() *Digest
func (d *Digest) MarshalBinary() ([]byte, error)
func (d *Digest) Reset()
Reset resets the Digest to its initial state.
func (d *Digest) Size() int
Size returns the output size of the hash function in bytes.
func (d *Digest) Sum(b []byte) []byte
Sum appends the current hash to b and returns the resulting slice. It does
not change the underlying hash state.
func (d *Digest) UnmarshalBinary(b []byte) error
func (d *Digest) Write(p []byte) (n int, err error)
Write absorbs more data into the hash's state.
func (d *Digest) padAndPermute()
padAndPermute appends the domain separation bits in dsbyte, applies the
multi-bitrate 10..1 padding rule, and permutes the state.
func (d *Digest) permute()
permute applies the KeccakF-1600 permutation.
func (d *Digest) read(out []byte) (n int, err error)
func (d *Digest) readGeneric(out []byte) (n int, err error)
read squeezes an arbitrary number of bytes from the sponge.
func (d *Digest) sum(b []byte) []byte
func (d *Digest) sumGeneric(b []byte) []byte
func (d *Digest) write(p []byte) (n int, err error)
func (d *Digest) writeGeneric(p []byte) (n int, err error)
type SHAKE struct {
initBlock []byte
}
func NewCShake128(N, S []byte) *SHAKE
NewCShake128 creates a new cSHAKE128 XOF.
N is used to define functions based on cSHAKE, it can be empty when
plain cSHAKE is desired. S is a customization byte string used for domain
separation. When N and S are both empty, this is equivalent to NewShake128.
func NewCShake256(N, S []byte) *SHAKE
NewCShake256 creates a new cSHAKE256 XOF.
N is used to define functions based on cSHAKE, it can be empty when
plain cSHAKE is desired. S is a customization byte string used for domain
separation. When N and S are both empty, this is equivalent to NewShake256.
func NewShake128() *SHAKE
NewShake128 creates a new SHAKE128 XOF.
func NewShake256() *SHAKE
NewShake256 creates a new SHAKE256 XOF.
func newCShake(N, S []byte, rate, outputLen int, dsbyte byte) *SHAKE
func (s *SHAKE) AppendBinary(b []byte) ([]byte, error)
func (s *SHAKE) BlockSize() int
func (s *SHAKE) Clone() *SHAKE
Clone returns a copy of the SHAKE context in its current state.
func (s *SHAKE) MarshalBinary() ([]byte, error)
func (s *SHAKE) Read(out []byte) (n int, err error)
func (s *SHAKE) Reset()
Reset resets the hash to initial state.
func (s *SHAKE) Size() int
func (s *SHAKE) Sum(in []byte) []byte
Sum appends a portion of output to b and returns the resulting slice.
The output length is selected to provide full-strength generic security:
32 bytes for SHAKE128 and 64 bytes for SHAKE256. It does not change the
underlying state. It panics if any output has already been read.
func (s *SHAKE) UnmarshalBinary(b []byte) error
func (s *SHAKE) Write(p []byte) (n int, err error)
Write absorbs more data into the hash's state. It panics if any output has
already been read.
type spongeDirection int
spongeDirection indicates the direction bytes are flowing through the
sponge.
const (
spongeAbsorbing spongeDirection = iota
spongeSqueezing
)
crypto/internal/fips140/sha512
func block(dig *Digest, p []byte)
func blockAMD64(dig *Digest, p []byte)
func blockAVX2(dig *Digest, p []byte)
func blockGeneric(dig *Digest, p []byte)
func consumeUint64(b []byte) ([]byte, uint64)
func init()
TYPES
type Digest struct {
h [8]uint64
x [chunk]byte
nx int
len uint64
}
Digest is a SHA-384, SHA-512, SHA-512/224, or SHA-512/256 hash.Hash
implementation.
func New() *Digest
New returns a new Digest computing the SHA-512 hash.
func New384() *Digest
New384 returns a new Digest computing the SHA-384 hash.
func New512_224() *Digest
New512_224 returns a new Digest computing the SHA-512/224 hash.
func New512_256() *Digest
New512_256 returns a new Digest computing the SHA-512/256 hash.
func (d *Digest) AppendBinary(b []byte) ([]byte, error)
func (d *Digest) BlockSize() int
func (d *Digest) MarshalBinary() ([]byte, error)
func (d *Digest) Reset()
func (d *Digest) Size() int
func (d *Digest) Sum(in []byte) []byte
func (d *Digest) UnmarshalBinary(b []byte) error
func (d *Digest) Write(p []byte) (nn int, err error)
func (d *Digest) checkSum() [size512]byte
crypto/internal/fips140/ssh
func Keys[Hash fips140.Hash](hash func() Hash, d Direction,
K, H, sessionID []byte,
ivKeyLen, keyLen, macKeyLen int,
) (ivKey, key, macKey []byte)
func init()
TYPES
type Direction struct {
ivTag []byte
keyTag []byte
macKeyTag []byte
}
var ServerKeys, ClientKeys Direction
crypto/internal/fips140/subtle
func ConstantTimeByteEq(x, y uint8) int
ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
func ConstantTimeCompare(x, y []byte) int
ConstantTimeCompare returns 1 if the two slices, x and y, have equal
contents and 0 otherwise. The time taken is a function of the length of the
slices and is independent of the contents. If the lengths of x and y do not
match it returns 0 immediately.
func ConstantTimeCopy(v int, x, y []byte)
ConstantTimeCopy copies the contents of y into x (a slice of equal length)
if v == 1. If v == 0, x is left unchanged. Its behavior is undefined if v
takes any other value.
func ConstantTimeEq(x, y int32) int
ConstantTimeEq returns 1 if x == y and 0 otherwise.
func ConstantTimeLessOrEq(x, y int) int
ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise. Its behavior is
undefined if x or y are negative or > 2**31 - 1.
func ConstantTimeSelect(v, x, y int) int
ConstantTimeSelect returns x if v == 1 and y if v == 0. Its behavior is
undefined if v takes any other value.
func XORBytes(dst, x, y []byte) int
XORBytes sets dst[i] = x[i] ^ y[i] for all i < n = min(len(x), len(y)),
returning n, the number of bytes written to dst.
If dst does not have length at least n, XORBytes panics without writing
anything to dst.
dst and x or y may overlap exactly or not at all, otherwise XORBytes may
panic.
func xorBytes(dst, a, b *byte, n int)
crypto/internal/fips140/tls12
func MasterSecret[H fips140.Hash](hash func() H, preMasterSecret, transcript []byte) []byte
MasterSecret implements the TLS 1.2 extended master secret derivation,
as defined in RFC 7627 and allowed by SP 800-135, Revision 1, Section 4.2.2.
func PRF[H fips140.Hash](hash func() H, secret []byte, label string, seed []byte, keyLen int) []byte
PRF implements the TLS 1.2 pseudo-random function, as defined in RFC 5246,
Section 5 and allowed by SP 800-135, Revision 1, Section 4.2.2.
func init()
func pHash[H fips140.Hash](hash func() H, result, secret, seed []byte)
pHash implements the P_hash function, as defined in RFC 5246, Section 5.
crypto/internal/fips140/tls13
func ExpandLabel[H fips140.Hash](hash func() H, secret []byte, label string, context []byte, length int) []byte
ExpandLabel implements HKDF-Expand-Label from RFC 8446, Section 7.1.
func TestingOnlyExporterSecret(s *ExporterMasterSecret) []byte
func deriveSecret[H fips140.Hash](hash func() H, secret []byte, label string, transcript fips140.Hash) []byte
func extract[H fips140.Hash](hash func() H, newSecret, currentSecret []byte) []byte
func init()
TYPES
type EarlySecret struct {
secret []byte
hash func() fips140.Hash
}
func NewEarlySecret[H fips140.Hash](hash func() H, psk []byte) *EarlySecret
func (s *EarlySecret) ClientEarlyTrafficSecret(transcript fips140.Hash) []byte
ClientEarlyTrafficSecret derives the client_early_traffic_secret from the
early secret and the transcript up to the ClientHello.
func (s *EarlySecret) EarlyExporterMasterSecret(transcript fips140.Hash) *ExporterMasterSecret
EarlyExporterMasterSecret derives the exporter_master_secret from the early
secret and the transcript up to the ClientHello.
func (s *EarlySecret) HandshakeSecret(sharedSecret []byte) *HandshakeSecret
func (s *EarlySecret) ResumptionBinderKey() []byte
type ExporterMasterSecret struct {
secret []byte
hash func() fips140.Hash
}
func (s *ExporterMasterSecret) Exporter(label string, context []byte, length int) []byte
type HandshakeSecret struct {
secret []byte
hash func() fips140.Hash
}
func (s *HandshakeSecret) ClientHandshakeTrafficSecret(transcript fips140.Hash) []byte
ClientHandshakeTrafficSecret derives the client_handshake_traffic_secret
from the handshake secret and the transcript up to the ServerHello.
func (s *HandshakeSecret) MasterSecret() *MasterSecret
func (s *HandshakeSecret) ServerHandshakeTrafficSecret(transcript fips140.Hash) []byte
ServerHandshakeTrafficSecret derives the server_handshake_traffic_secret
from the handshake secret and the transcript up to the ServerHello.
type MasterSecret struct {
secret []byte
hash func() fips140.Hash
}
func (s *MasterSecret) ClientApplicationTrafficSecret(transcript fips140.Hash) []byte
ClientApplicationTrafficSecret derives the
client_application_traffic_secret_0 from the master secret and the
transcript up to the server Finished.
func (s *MasterSecret) ExporterMasterSecret(transcript fips140.Hash) *ExporterMasterSecret
ExporterMasterSecret derives the exporter_master_secret from the master
secret and the transcript up to the server Finished.
func (s *MasterSecret) ResumptionMasterSecret(transcript fips140.Hash) []byte
ResumptionMasterSecret derives the resumption_master_secret from the master
secret and the transcript up to the client Finished.
func (s *MasterSecret) ServerApplicationTrafficSecret(transcript fips140.Hash) []byte
ServerApplicationTrafficSecret derives the
server_application_traffic_secret_0 from the master secret and the
transcript up to the server Finished.
crypto/internal/fips140deps
crypto/internal/fips140deps/byteorder
func BEAppendUint16(b []byte, v uint16) []byte
func BEAppendUint32(b []byte, v uint32) []byte
func BEAppendUint64(b []byte, v uint64) []byte
func BEPutUint16(b []byte, v uint16)
func BEPutUint32(b []byte, v uint32)
func BEPutUint64(b []byte, v uint64)
func BEUint32(b []byte) uint32
func BEUint64(b []byte) uint64
func LEPutUint64(b []byte, v uint64)
func LEUint16(b []byte) uint16
func LEUint64(b []byte) uint64
crypto/internal/fips140deps/cpu
crypto/internal/fips140deps/godebug
func Value(name string) string
TYPES
type Setting godebug.Setting
func New(name string) *Setting
func (s *Setting) Value() string
crypto/internal/fips140only
func ApprovedHash(h hash.Hash) bool
func ApprovedRandomReader(r io.Reader) bool
crypto/internal/fips140test
crypto/internal/hpke
func ParseHPKEPrivateKey(kemID uint16, bytes []byte) (*ecdh.PrivateKey, error)
func ParseHPKEPublicKey(kemID uint16, bytes []byte) (*ecdh.PublicKey, error)
func suiteID(kemID, kdfID, aeadID uint16) []byte
TYPES
type AEADID uint16
type KDFID uint16
type KemID uint16
type Receipient struct {
*context
}
func SetupReceipient(kemID, kdfID, aeadID uint16, priv *ecdh.PrivateKey, info, encPubEph []byte) (*Receipient, error)
func (r *Receipient) Open(aad, ciphertext []byte) ([]byte, error)
func (ctx Receipient) incrementNonce()
func (ctx Receipient) nextNonce() []byte
type Sender struct {
*context
}
func SetupSender(kemID, kdfID, aeadID uint16, pub *ecdh.PublicKey, info []byte) ([]byte, *Sender, error)
func (s *Sender) Seal(aad, plaintext []byte) ([]byte, error)
func (ctx Sender) incrementNonce()
func (ctx Sender) nextNonce() []byte
type context struct {
aead cipher.AEAD
sharedSecret []byte
suiteID []byte
key []byte
baseNonce []byte
exporterSecret []byte
seqNum uint128
}
func newContext(sharedSecret []byte, kemID, kdfID, aeadID uint16, info []byte) (*context, error)
func (ctx *context) incrementNonce()
func (ctx *context) nextNonce() []byte
type dhKEM struct {
dh ecdh.Curve
kdf hkdfKDF
suiteID []byte
nSecret uint16
}
dhKEM implements the KEM specified in RFC 9180, Section 4.1.
func newDHKem(kemID uint16) (*dhKEM, error)
func (dh *dhKEM) Decap(encPubEph []byte, secRecipient *ecdh.PrivateKey) ([]byte, error)
func (dh *dhKEM) Encap(pubRecipient *ecdh.PublicKey) (sharedSecret []byte, encapPub []byte, err error)
func (dh *dhKEM) ExtractAndExpand(dhKey, kemContext []byte) []byte
type hkdfKDF struct {
hash crypto.Hash
}
func (kdf *hkdfKDF) LabeledExpand(suiteID []byte, randomKey []byte, label string, info []byte, length uint16) []byte
func (kdf *hkdfKDF) LabeledExtract(sid []byte, salt []byte, label string, inputKey []byte) []byte
type uint128 struct {
hi, lo uint64
}
func (u uint128) addOne() uint128
func (u uint128) bitLen() int
func (u uint128) bytes() []byte
crypto/internal/impl
func List(pkg string) []string
List returns the names of all alternative implementations registered for the
given package, whether available or not. The implicit base implementation is
not included.
func Register(pkg, name string, available *bool)
Register records an alternative implementation of a cryptographic primitive.
The implementation might be available or not based on CPU support.
If available is false, the implementation is unavailable and can't be tested
on this machine. If available is true, it can be set to false to disable the
implementation. If all alternative implementations but one are disabled,
the remaining one must be used (i.e. disabling one implementation must
not implicitly disable any other). Each package has an implicit base
implementation that is selected when all alternatives are unavailable
or disabled. pkg must be the package name, not path (e.g. "aes" not
"crypto/aes").
func Reset(pkg string)
func Select(pkg, name string) bool
Select disables all implementations for the given package except the one
with the given name. If name is empty, the base implementation is selected.
It returns whether the selected implementation is available.
func available(pkg, name string) bool
TYPES
type implementation struct {
Package string
Name string
Available bool
Toggle *bool
}
crypto/internal/randutil
func MaybeReadByte(r io.Reader)
MaybeReadByte reads a single byte from r with 50% probability. This is
used to ensure that callers do not depend on non-guaranteed behaviour, e.g.
assuming that rsa.GenerateKey is deterministic w.r.t. a given random stream.
This does not affect tests that pass a stream of fixed bytes as the random
source (e.g. a zeroReader).
crypto/internal/sysrand
func Read(b []byte)
Read fills b with cryptographically secure random bytes from the operating
system. It always fills b entirely and crashes the program irrecoverably if
an error is encountered. The operating system APIs are documented to never
return an error on all but legacy Linux systems.
func fatal(string)
fatal is [runtime.fatal], pushed via linkname.
func read(b []byte) error
func urandomRead(b []byte) error
func warnBlocked()
crypto/internal/sysrand/internal/seccomp
func DisableGetrandom() error
DisableGetrandom makes future calls to getrandom(2) fail with ENOSYS.
It applies only to the current thread and to any programs executed from it.
Callers should use runtime.LockOSThread in a dedicated goroutine.
crypto/md5
func New() hash.Hash
New returns a new hash.Hash computing the MD5 checksum. The Hash
also implements encoding.BinaryMarshaler, encoding.BinaryAppender and
encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of
the hash.
func Sum(data []byte) [Size]byte
Sum returns the MD5 checksum of the data.
func block(dig *digest, p []byte)
func blockGeneric(dig *digest, p []byte)
func consumeUint32(b []byte) ([]byte, uint32)
func consumeUint64(b []byte) ([]byte, uint64)
func init()
TYPES
type digest struct {
s [4]uint32
x [BlockSize]byte
nx int
len uint64
}
digest represents the partial evaluation of a checksum.
func (d *digest) AppendBinary(b []byte) ([]byte, error)
func (d *digest) BlockSize() int
func (d *digest) MarshalBinary() ([]byte, error)
func (d *digest) Reset()
func (d *digest) Size() int
func (d *digest) Sum(in []byte) []byte
func (d *digest) UnmarshalBinary(b []byte) error
func (d *digest) Write(p []byte) (nn int, err error)
func (d *digest) checkSum() [Size]byte
crypto/mlkem
crypto/pbkdf2
func Key[Hash hash.Hash](h func() Hash, password string, salt []byte, iter, keyLength int) ([]byte, error)
Key derives a key from the password, salt and iteration count, returning a
[]byte of length keyLength that can be used as cryptographic key. The key is
derived based on the method described as PBKDF2 with the HMAC variant using
the supplied hash function.
For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you
can get a derived key for e.g. AES-256 (which needs a 32-byte key) by doing:
dk := pbkdf2.Key(sha1.New, []byte("some password"), salt, 4096, 32)
Remember to get a good random salt. At least 8 bytes is recommended by the
RFC.
Using a higher iteration count will increase the cost of an exhaustive
search but will also make derivation proportionally slower.
crypto/rand
func Int(rand io.Reader, max *big.Int) (n *big.Int, err error)
Int returns a uniform random value in [0, max). It panics if max <= 0,
and returns an error if rand.Read returns one.
func Prime(rand io.Reader, bits int) (*big.Int, error)
Prime returns a number of the given bit length that is prime with high
probability. Prime will return error for any error returned by rand.Read or
if bits < 2.
func Read(b []byte) (n int, err error)
Read fills b with cryptographically secure random bytes. It never returns an
error, and always fills b entirely.
Read calls io.ReadFull on Reader and crashes the program irrecoverably if
an error is returned. The default Reader uses operating system APIs that are
documented to never return an error on all but legacy Linux systems.
func Text() string
Text returns a cryptographically random string using the standard RFC
4648 base32 alphabet for use when a secret string, token, password, or
other text is needed. The result contains at least 128 bits of randomness,
enough to prevent brute force guessing attacks and to make the likelihood
of collisions vanishingly small. A future version may return longer texts as
needed to maintain those properties.
func fatal(string)
fatal is [runtime.fatal], pushed via linkname.
func init()
TYPES
type reader struct {
drbg.DefaultReader
}
func (r *reader) Read(b []byte) (n int, err error)
crypto/rc4
crypto/rsa
func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error)
DecryptOAEP decrypts ciphertext using RSA-OAEP.
OAEP is parameterised by a hash function that is used as a random oracle.
Encryption and decryption of a given message must use the same hash function
and sha256.New() is a reasonable choice.
The random parameter is legacy and ignored, and it can be nil.
The label parameter must match the value given when encrypting. See
EncryptOAEP for details.
func DecryptPKCS1v15(random io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error)
DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from
PKCS #1 v1.5. The random parameter is legacy and ignored, and it can be nil.
Note that whether this function returns an error or not discloses
secret information. If an attacker can cause this function to run
repeatedly and learn whether each instance returned an error then they
can decrypt and forge signatures as if they had the private key. See
DecryptPKCS1v15SessionKey for a way of solving this problem.
func DecryptPKCS1v15SessionKey(random io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error
DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding
scheme from PKCS #1 v1.5. The random parameter is legacy and ignored,
and it can be nil.
DecryptPKCS1v15SessionKey returns an error if the ciphertext is the wrong
length or if the ciphertext is greater than the public modulus. Otherwise,
no error is returned. If the padding is valid, the resulting plaintext
message is copied into key. Otherwise, key is unchanged. These alternatives
occur in constant time. It is intended that the user of this function
generate a random session key beforehand and continue the protocol with the
resulting value.
Note that if the session key is too small then it may be possible for an
attacker to brute-force it. If they can do that then they can learn whether
a random value was used (because it'll be different for the same ciphertext)
and thus whether the padding was correct. This also defeats the point of
this function. Using at least a 16-byte key will protect against this
attack.
This method implements protections against Bleichenbacher chosen ciphertext
attacks [0] described in RFC 3218 Section 2.3.2 [1]. While these
protections make a Bleichenbacher attack significantly more difficult,
the protections are only effective if the rest of the protocol which uses
DecryptPKCS1v15SessionKey is designed with these considerations in mind. In
particular, if any subsequent operations which use the decrypted session key
leak any information about the key (e.g. whether it is a static or random
key) then the mitigations are defeated. This method must be used extremely
carefully, and typically should only be used when absolutely necessary for
compatibility with an existing protocol (such as TLS) that is designed with
these properties in mind.
- [0] “Chosen Ciphertext Attacks Against Protocols Based on the RSA
Encryption Standard PKCS #1”, Daniel Bleichenbacher, Advances in
Cryptology (Crypto '98)
- [1] RFC 3218, Preventing the Million Message Attack on CMS,
func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)
EncryptOAEP encrypts the given message with RSA-OAEP.
OAEP is parameterised by a hash function that is used as a random oracle.
Encryption and decryption of a given message must use the same hash function
and sha256.New() is a reasonable choice.
The random parameter is used as a source of entropy to ensure that
encrypting the same message twice doesn't result in the same ciphertext.
Most applications should use crypto/rand.Reader as random.
The label parameter may contain arbitrary data that will not be encrypted,
but which gives important context to the message. For example, if a given
public key is used to encrypt two types of messages then distinct label
values could be used to ensure that a ciphertext for one purpose cannot be
used for another by an attacker. If not required it can be empty.
The message must be no longer than the length of the public modulus minus
twice the hash length, minus a further 2.
func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error)
EncryptPKCS1v15 encrypts the given message with RSA and the padding scheme
from PKCS #1 v1.5. The message must be no longer than the length of the
public modulus minus 11 bytes.
The random parameter is used as a source of entropy to ensure that
encrypting the same message twice doesn't result in the same ciphertext.
Most applications should use crypto/rand.Reader as random. Note that the
returned ciphertext does not depend deterministically on the bytes read from
random, and may change between calls and/or between versions.
WARNING: use of this function to encrypt plaintexts other than session keys
is dangerous. Use RSA OAEP in new protocols.
func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error)
SignPKCS1v15 calculates the signature of hashed using 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 function. If hash is zero, hashed is
signed directly. This isn't advisable except for interoperability.
The random parameter is legacy and ignored, and it can be nil.
This function is deterministic. Thus, if the set of possible messages is
small, an attacker may be able to build a map from messages to signatures
and identify the signed messages. As ever, signatures provide authenticity,
not confidentiality.
func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, digest []byte, opts *PSSOptions) ([]byte, error)
SignPSS calculates the signature of digest using PSS.
digest must be the result of hashing the input message using the given hash
function. The opts argument may be nil, in which case sensible defaults are
used. If opts.Hash is set, it overrides hash.
The signature is randomized depending on the message, key, and salt size,
using bytes from rand. Most applications should use crypto/rand.Reader as
rand.
func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error
VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature. 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 returning a nil error.
If hash is zero then hashed is used directly. This isn't advisable except
for interoperability.
The inputs are not considered confidential, and may leak through timing side
channels, or if an attacker has control of part of the inputs.
func VerifyPSS(pub *PublicKey, hash crypto.Hash, digest []byte, sig []byte, opts *PSSOptions) error
VerifyPSS verifies a PSS signature.
A valid signature is indicated by returning a nil error. digest must be
the result of hashing the input message using the given hash function.
The opts argument may be nil, in which case sensible defaults are used.
opts.Hash is ignored.
The inputs are not considered confidential, and may leak through timing side
channels, or if an attacker has control of part of the inputs.
func bigIntEqual(a, b *big.Int) bool
bigIntEqual reports whether a and b are equal leaking only their bit length
through timing side-channels.
func boringPrivateKey(priv *PrivateKey) (*boring.PrivateKeyRSA, error)
func boringPublicKey(pub *PublicKey) (*boring.PublicKeyRSA, error)
func checkFIPS140OnlyPrivateKey(priv *PrivateKey) error
func checkFIPS140OnlyPublicKey(pub *PublicKey) error
func checkKeySize(size int) error
func checkPublicKeySize(k *PublicKey) error
func decryptOAEP(hash, mgfHash hash.Hash, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error)
func decryptPKCS1v15(priv *PrivateKey, ciphertext []byte) (valid int, em []byte, index int, err error)
decryptPKCS1v15 decrypts ciphertext using priv. It returns one or zero
in valid that indicates whether the plaintext was correctly structured.
In either case, the plaintext is returned in em so that it may be read
independently of whether it was valid in order to maintain constant memory
access patterns. If the plaintext was valid then index contains the index of
the original message in em, to allow constant time padding removal.
func fipsError(err error) error
func fipsError2[T any](x T, err error) (T, error)
func fipsPrivateKey(priv *PrivateKey) (*rsa.PrivateKey, error)
func fipsPublicKey(pub *PublicKey) (*rsa.PublicKey, error)
func init()
func nonZeroRandomBytes(s []byte, random io.Reader) (err error)
nonZeroRandomBytes fills the given slice with non-zero random octets.
func privateKeyEqual(k1, k2 *PrivateKey) bool
func publicKeyEqual(k1, k2 *PublicKey) bool
TYPES
type CRTValue struct {
}
CRTValue contains the precomputed Chinese remainder theorem values.
type OAEPOptions struct {
Hash crypto.Hash
MGFHash crypto.Hash
Label []byte
}
OAEPOptions is an interface for passing options to OAEP decryption using the
crypto.Decrypter interface.
type PKCS1v15DecryptOptions struct {
SessionKeyLen int
}
PKCS1v15DecryptOptions is for passing options to PKCS #1 v1.5 decryption
using the crypto.Decrypter interface.
type PSSOptions struct {
SaltLength int
Hash crypto.Hash
}
PSSOptions contains options for creating and verifying PSS signatures.
func (opts *PSSOptions) HashFunc() crypto.Hash
HashFunc returns opts.Hash so that PSSOptions implements crypto.SignerOpts.
func (opts *PSSOptions) saltLength() int
type PrecomputedValues struct {
CRTValues []CRTValue
fips *rsa.PrivateKey
}
type PrivateKey struct {
Precomputed PrecomputedValues
}
A PrivateKey represents an RSA key
func GenerateKey(random io.Reader, bits int) (*PrivateKey, error)
GenerateKey generates a random RSA private key of the given bit size.
If bits is less than 1024, GenerateKey returns an error. See the "[Minimum
key size]" section for further details.
Most applications should use crypto/rand.Reader as rand. Note that the
returned key does not depend deterministically on the bytes read from rand,
and may change between calls and/or between versions.
[Minimum key size]: #hdr-Minimum_key_size
func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (*PrivateKey, error)
GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit
size and the given random source.
Table 1 in "On the Security of Multi-prime RSA" suggests maximum numbers of
primes for a given bit size.
Although the public keys are compatible (actually, indistinguishable) from
the 2-prime case, the private keys are not. Thus it may not be possible to
export multi-prime private keys in certain formats or to subsequently import
them into other code.
This package does not implement CRT optimizations for multi-prime RSA,
so the keys with more than two primes will have worse performance.
Deprecated: The use of this function with a number of primes different
from two is not recommended for the above security, compatibility, and
performance reasons. Use GenerateKey instead.
func copyPrivateKey(k *PrivateKey) PrivateKey
func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)
Decrypt decrypts ciphertext with priv. If opts is nil or of type
*PKCS1v15DecryptOptions then PKCS #1 v1.5 decryption is performed. Otherwise
opts must have type *OAEPOptions and OAEP decryption is done.
func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool
Equal reports whether priv and x have equivalent values. It ignores
Precomputed values.
func (priv *PrivateKey) Precompute()
Precompute performs some calculations that speed up private key operations
in the future. It is safe to run on non-validated private keys.
func (priv *PrivateKey) Public() crypto.PublicKey
Public returns the public key corresponding to priv.
func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
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 be used. digest must be the result of hashing the input message using
opts.HashFunc().
This method implements crypto.Signer, which is an interface to support
keys where the private part is kept in, for example, a hardware module.
Common uses should use the Sign* functions in this package directly.
func (priv *PrivateKey) Validate() error
Validate performs basic sanity checks on the key. It returns nil if the key
is valid, or else an error describing a problem.
It runs faster on valid keys if run after [Precompute].
func (priv *PrivateKey) precompute() (PrecomputedValues, error)
func (priv *PrivateKey) precomputeLegacy() (PrecomputedValues, error)
type PublicKey struct {
}
A PublicKey represents the public part of an RSA key.
The value of the modulus N is considered secret by this library and
protected from leaking through timing side-channels. However, neither
the value of the exponent E nor the precise bit size of N are similarly
protected.
func copyPublicKey(k *PublicKey) PublicKey
func (pub *PublicKey) Equal(x crypto.PublicKey) bool
Equal reports whether pub and x have the same value.
func (pub *PublicKey) Size() int
Size returns the modulus size in bytes. Raw signatures and ciphertexts for
or by this public key will have the same size.
type boringPriv struct {
key *boring.PrivateKeyRSA
orig PrivateKey
}
type boringPub struct {
key *boring.PublicKeyRSA
orig PublicKey
}
crypto/sha1
func New() hash.Hash
New returns a new hash.Hash computing the SHA1 checksum. The Hash
also implements encoding.BinaryMarshaler, encoding.BinaryAppender and
encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of
the hash.
func Sum(data []byte) [Size]byte
Sum returns the SHA-1 checksum of the data.
func block(dig *digest, p []byte)
func blockAMD64(dig *digest, p []byte)
func blockAVX2(dig *digest, p []byte)
func blockGeneric(dig *digest, p []byte)
blockGeneric is a portable, pure Go version of the SHA-1 block step.
It's used by sha1block_generic.go and tests.
func consumeUint32(b []byte) ([]byte, uint32)
func consumeUint64(b []byte) ([]byte, uint64)
func init()
TYPES
type digest struct {
h [5]uint32
x [chunk]byte
nx int
len uint64
}
digest represents the partial evaluation of a checksum.
func (d *digest) AppendBinary(b []byte) ([]byte, error)
func (d *digest) BlockSize() int
func (d *digest) ConstantTimeSum(in []byte) []byte
ConstantTimeSum computes the same result of Sum but in constant time
func (d *digest) MarshalBinary() ([]byte, error)
func (d *digest) Reset()
func (d *digest) Size() int
func (d *digest) Sum(in []byte) []byte
func (d *digest) UnmarshalBinary(b []byte) error
func (d *digest) Write(p []byte) (nn int, err error)
func (d *digest) checkSum() [Size]byte
func (d *digest) constSum() [Size]byte
crypto/sha256
func New() hash.Hash
New returns a new hash.Hash computing the SHA256 checksum. The Hash
also implements encoding.BinaryMarshaler, encoding.BinaryAppender and
encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of
the hash.
func New224() hash.Hash
New224 returns a new hash.Hash computing the SHA224 checksum. The Hash
also implements encoding.BinaryMarshaler, encoding.BinaryAppender and
encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of
the hash.
func Sum224(data []byte) [Size224]byte
Sum224 returns the SHA224 checksum of the data.
func Sum256(data []byte) [Size]byte
Sum256 returns the SHA256 checksum of the data.
func init()
crypto/sha3
func Sum224(data []byte) [28]byte
Sum224 returns the SHA3-224 hash of data.
func Sum256(data []byte) [32]byte
Sum256 returns the SHA3-256 hash of data.
func Sum384(data []byte) [48]byte
Sum384 returns the SHA3-384 hash of data.
func Sum512(data []byte) [64]byte
Sum512 returns the SHA3-512 hash of data.
func SumSHAKE128(data []byte, length int) []byte
SumSHAKE128 applies the SHAKE128 extendable output function to data and
returns an output of the given length in bytes.
func SumSHAKE256(data []byte, length int) []byte
SumSHAKE256 applies the SHAKE256 extendable output function to data and
returns an output of the given length in bytes.
func init()
func sumSHAKE128(out, data []byte, length int) []byte
func sumSHAKE256(out, data []byte, length int) []byte
TYPES
type SHA3 struct {
s sha3.Digest
}
SHA3 is an instance of a SHA-3 hash. It implements hash.Hash.
func New224() *SHA3
New224 creates a new SHA3-224 hash.
func New256() *SHA3
New256 creates a new SHA3-256 hash.
func New384() *SHA3
New384 creates a new SHA3-384 hash.
func New512() *SHA3
New512 creates a new SHA3-512 hash.
func (s *SHA3) AppendBinary(p []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender.
func (s *SHA3) BlockSize() int
BlockSize returns the hash's rate.
func (s *SHA3) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler.
func (s *SHA3) Reset()
Reset resets the hash to its initial state.
func (s *SHA3) Size() int
Size returns the number of bytes Sum will produce.
func (s *SHA3) Sum(b []byte) []byte
Sum appends the current hash to b and returns the resulting slice.
func (s *SHA3) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (s *SHA3) Write(p []byte) (n int, err error)
Write absorbs more data into the hash's state.
type SHAKE struct {
s sha3.SHAKE
}
SHAKE is an instance of a SHAKE extendable output function.
func NewCSHAKE128(N, S []byte) *SHAKE
NewCSHAKE128 creates a new cSHAKE128 XOF.
N is used to define functions based on cSHAKE, it can be empty when
plain cSHAKE is desired. S is a customization byte string used for domain
separation. When N and S are both empty, this is equivalent to NewSHAKE128.
func NewCSHAKE256(N, S []byte) *SHAKE
NewCSHAKE256 creates a new cSHAKE256 XOF.
N is used to define functions based on cSHAKE, it can be empty when
plain cSHAKE is desired. S is a customization byte string used for domain
separation. When N and S are both empty, this is equivalent to NewSHAKE256.
func NewSHAKE128() *SHAKE
NewSHAKE128 creates a new SHAKE128 XOF.
func NewSHAKE256() *SHAKE
NewSHAKE256 creates a new SHAKE256 XOF.
func (s *SHAKE) AppendBinary(p []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender.
func (s *SHAKE) BlockSize() int
BlockSize returns the rate of the XOF.
func (s *SHAKE) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler.
func (s *SHAKE) Read(p []byte) (n int, err error)
Read squeezes more output from the XOF.
Any call to Write after a call to Read will panic.
func (s *SHAKE) Reset()
Reset resets the XOF to its initial state.
func (s *SHAKE) UnmarshalBinary(data []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (s *SHAKE) Write(p []byte) (n int, err error)
Write absorbs more data into the XOF's state.
It panics if any output has already been read.
crypto/sha512
func New() hash.Hash
New returns a new hash.Hash computing the SHA-512 checksum. The Hash
also implements encoding.BinaryMarshaler, encoding.BinaryAppender and
encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of
the hash.
func New384() hash.Hash
New384 returns a new hash.Hash computing the SHA-384 checksum. The Hash
also implements encoding.BinaryMarshaler, encoding.BinaryAppender and
encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of
the hash.
func New512_224() hash.Hash
New512_224 returns a new hash.Hash computing the SHA-512/224 checksum.
The Hash also implements encoding.BinaryMarshaler, encoding.BinaryAppender
and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state
of the hash.
func New512_256() hash.Hash
New512_256 returns a new hash.Hash computing the SHA-512/256 checksum.
The Hash also implements encoding.BinaryMarshaler, encoding.BinaryAppender
and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state
of the hash.
func Sum384(data []byte) [Size384]byte
Sum384 returns the SHA384 checksum of the data.
func Sum512(data []byte) [Size]byte
Sum512 returns the SHA512 checksum of the data.
func Sum512_224(data []byte) [Size224]byte
Sum512_224 returns the Sum512/224 checksum of the data.
func Sum512_256(data []byte) [Size256]byte
Sum512_256 returns the Sum512/256 checksum of the data.
func init()
crypto/subtle
func ConstantTimeByteEq(x, y uint8) int
ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
func ConstantTimeCompare(x, y []byte) int
ConstantTimeCompare returns 1 if the two slices, x and y, have equal
contents and 0 otherwise. The time taken is a function of the length of the
slices and is independent of the contents. If the lengths of x and y do not
match it returns 0 immediately.
func ConstantTimeCopy(v int, x, y []byte)
ConstantTimeCopy copies the contents of y into x (a slice of equal length)
if v == 1. If v == 0, x is left unchanged. Its behavior is undefined if v
takes any other value.
func ConstantTimeEq(x, y int32) int
ConstantTimeEq returns 1 if x == y and 0 otherwise.
func ConstantTimeLessOrEq(x, y int) int
ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise. Its behavior is
undefined if x or y are negative or > 2**31 - 1.
func ConstantTimeSelect(v, x, y int) int
ConstantTimeSelect returns x if v == 1 and y if v == 0. Its behavior is
undefined if v takes any other value.
func WithDataIndependentTiming(f func())
WithDataIndependentTiming enables architecture specific features which
ensure that the timing of specific instructions is independent of their
inputs before executing f. On f returning it disables these features.
WithDataIndependentTiming should only be used when f is written to make
use of constant-time operations. WithDataIndependentTiming does not make
variable-time code constant-time.
WithDataIndependentTiming may lock the current goroutine to the OS thread
for the duration of f. Calls to WithDataIndependentTiming may be nested.
On Arm64 processors with FEAT_DIT,
WithDataIndependentTiming enables PSTATE.DIT. See
Currently, on all other architectures WithDataIndependentTiming executes f
immediately with no other side-effects.
func XORBytes(dst, x, y []byte) int
XORBytes sets dst[i] = x[i] ^ y[i] for all i < n = min(len(x), len(y)),
returning n, the number of bytes written to dst.
If dst does not have length at least n, XORBytes panics without writing
anything to dst.
dst and x or y may overlap exactly or not at all, otherwise XORBytes may
panic.
crypto/tls
func CipherSuiteName(id uint16) string
CipherSuiteName returns the standard name for the passed cipher suite
ID (e.g. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), or a fallback
representation of the ID value if the cipher suite is not implemented by
this package.
func Listen(network, laddr string, config *Config) (net.Listener, error)
Listen creates a TLS listener accepting connections on the given network
address using net.Listen. The configuration config must be non-nil and must
include at least one certificate or else set GetCertificate.
func NewListener(inner net.Listener, config *Config) net.Listener
NewListener creates a Listener which accepts connections from an inner
Listener and wraps each connection with Server. The configuration config
must be non-nil and must include at least one certificate or else set
GetCertificate.
func VersionName(version uint16) string
VersionName returns the name for the provided TLS version number (e.g.
"TLS 1.3"), or a fallback representation of the value if the version is not
implemented by this package.
func _()
func addBytesWithLength(b *cryptobyte.Builder, v []byte, n int)
addBytesWithLength appends a sequence of bytes to the cryptobyte.Builder. If
the length of the sequence is not the value specified, it produces an error.
func addUint64(b *cryptobyte.Builder, v uint64)
addUint64 appends a big-endian, 64-bit value to the cryptobyte.Builder.
func aesgcmPreferred(ciphers []uint16) bool
aesgcmPreferred returns whether the first known cipher in the preference
list is an AES-GCM cipher, implying the peer has hardware support for it.
func buildRetryConfigList(keys []EncryptedClientHelloKey) ([]byte, error)
func certificatesToBytesSlice(certs []*x509.Certificate) [][]byte
func checkALPN(clientProtos []string, serverProto string, quic bool) error
checkALPN ensure that the server's choice of ALPN protocol is compatible
with the protocols that we advertised in the Client Hello.
func checkKeySize(n int) (max int, ok bool)
func cipher3DES(key, iv []byte, isRead bool) any
func cipherAES(key, iv []byte, isRead bool) any
func cipherRC4(key, iv []byte, isRead bool) any
func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash
cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler
interfaces implemented by standard library hashes to clone the state of in
to a new instance of h. It returns nil if the operation fails.
func computeAndUpdateOuterECHExtension(outer, inner *clientHelloMsg, ech *echClientContext, useKey bool) error
func computeAndUpdatePSK(m *clientHelloMsg, binderKey []byte, transcript hash.Hash, finishedHash func([]byte, hash.Hash) []byte) error
func curveForCurveID(id CurveID) (ecdh.Curve, bool)
func curveIDForCurve(curve ecdh.Curve) (CurveID, bool)
func decryptECHPayload(context *hpke.Receipient, hello, payload []byte) ([]byte, error)
func defaultCipherSuites() []uint16
func ekmFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte) func(string, []byte, int) ([]byte, error)
ekmFromMasterSecret generates exported keying material as defined in RFC
5705.
func encodeInnerClientHello(inner *clientHelloMsg, maxNameLength int) ([]byte, error)
func extMasterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, transcript []byte) []byte
extMasterFromPreMasterSecret generates the extended master secret from the
pre-master secret. See RFC 7627.
func extractPadding(payload []byte) (toRemove int, good byte)
extractPadding returns, in constant time, the length of the padding to
remove from the end of payload. It also returns a byte which is equal to 255
if the padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2.
func fipsAllowCert(c *x509.Certificate) bool
func fipsAllowChain(chain []*x509.Certificate) bool
func fipsAllowedChains(chains [][]*x509.Certificate) ([][]*x509.Certificate, error)
fipsAllowedChains returns chains that are allowed to be used in a TLS
connection based on the current fips140tls enforcement setting.
If fips140tls is not required, the chains are returned as-is with no
processing. Otherwise, the returned chains are filtered to only those
allowed by FIPS 140-3. If this results in no chains it returns an error.
func generateECDHEKey(rand io.Reader, curveID CurveID) (*ecdh.PrivateKey, error)
generateECDHEKey returns a PrivateKey that implements Diffie-Hellman
according to RFC 8446, Section 4.2.8.2.
func generateOuterECHExt(id uint8, kdfID, aeadID uint16, encodedKey []byte, payload []byte) ([]byte, error)
func hashForServerKeyExchange(sigType uint8, hashFunc crypto.Hash, version uint16, slices ...[]byte) []byte
hashForServerKeyExchange hashes the given slices and returns their digest
using the given hash function (for TLS 1.2) or using a default based on the
sigType (for earlier TLS versions). For Ed25519 signatures, which don't do
pre-hashing, it returns the concatenation of the slices.
func hostnameInSNI(name string) string
hostnameInSNI converts name into an appropriate hostname for SNI. Literal IP
addresses and absolute FQDNs are not permitted as SNI values. See RFC 6066,
Section 3.
func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool
illegalClientHelloChange reports whether the two ClientHello messages are
different, with the exception of the changes allowed before and after a
HelloRetryRequest. See RFC 8446, Section 4.1.2.
func init()
func isPQKeyExchange(curve CurveID) bool
func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool
func isTLS13OnlyKeyExchange(curve CurveID) bool
func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte)
keysFromMasterSecret generates the connection keys from the master secret,
given the lengths of the MAC key, cipher key and IV, as defined in RFC 2246,
Section 6.3.
func legacyTypeAndHashFromPublicKey(pub crypto.PublicKey) (sigType uint8, hash crypto.Hash, err error)
legacyTypeAndHashFromPublicKey returns the fixed signature type and
crypto.Hash for a given public key used with TLS 1.0 and 1.1, before the
introduction of signature algorithm negotiation.
func macSHA1(key []byte) hash.Hash
macSHA1 returns a SHA-1 based constant time MAC.
func macSHA256(key []byte) hash.Hash
macSHA256 returns a SHA-256 based MAC. This is only supported in TLS 1.2 and
is currently only used in disabled-by-default cipher suites.
func marshalCertificate(b *cryptobyte.Builder, certificate Certificate)
func marshalEncryptedClientHelloConfigList(configs []EncryptedClientHelloKey) ([]byte, error)
func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte) []byte
masterFromPreMasterSecret generates the master secret from the pre-master
secret. See RFC 5246, Section 8.1.
func md5SHA1Hash(slices [][]byte) []byte
md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the
concatenation of an MD5 and SHA1 hash.
func negotiateALPN(serverProtos, clientProtos []string, quic bool) (string, error)
negotiateALPN picks a shared ALPN protocol that both sides support in server
preference order. If ALPN is not configured or the peer doesn't support it,
it returns "" and no error.
func newConstantTimeHash(h func() hash.Hash) func() hash.Hash
func noEKMBecauseNoEMS(label string, context []byte, length int) ([]byte, error)
noEKMBecauseNoEMS is used as a value of ConnectionState.ekm when Extended
Master Secret is not negotiated and thus we wish to fail all key-material
export requests.
func noEKMBecauseRenegotiation(label string, context []byte, length int) ([]byte, error)
noEKMBecauseRenegotiation is used as a value of ConnectionState.ekm when
renegotiation is enabled and thus we wish to fail all key-material export
requests.
func pHash(result, secret, seed []byte, hash func() hash.Hash)
pHash implements the P_hash function, as defined in RFC 4346, Section 5.
func parseECHConfig(enc []byte) (skip bool, ec echConfig, err error)
func parseECHExt(ext []byte) (echType echExtType, cs echCipher, configID uint8, encap []byte, payload []byte, err error)
func parsePrivateKey(der []byte) (crypto.PrivateKey, error)
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.
OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
func prf10(secret []byte, label string, seed []byte, keyLen int) []byte
prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246,
Section 5.
func quicError(err error) error
quicError ensures err is an AlertError. If err is not already, quicError
wraps it with alertInternalError.
func readUint16LengthPrefixed(s *cryptobyte.String, out *[]byte) bool
readUint16LengthPrefixed acts like s.ReadUint16LengthPrefixed, but targets a
[]byte instead of a cryptobyte.String.
func readUint24LengthPrefixed(s *cryptobyte.String, out *[]byte) bool
readUint24LengthPrefixed acts like s.ReadUint24LengthPrefixed, but targets a
[]byte instead of a cryptobyte.String.
func readUint64(s *cryptobyte.String, out *uint64) bool
readUint64 decodes a big-endian, 64-bit value into out and advances over it.
It reports whether the read was successful.
func readUint8LengthPrefixed(s *cryptobyte.String, out *[]byte) bool
readUint8LengthPrefixed acts like s.ReadUint8LengthPrefixed, but targets a
[]byte instead of a cryptobyte.String.
func requiresClientCert(c ClientAuthType) bool
requiresClientCert reports whether the ClientAuthType requires a client
certificate to be provided.
func roundUp(a, b int) int
func sha1Hash(slices [][]byte) []byte
sha1Hash calculates a SHA1 hash over the given byte slices.
func signedMessage(sigHash crypto.Hash, context string, transcript hash.Hash) []byte
signedMessage returns the pre-hashed (if necessary) message to be signed by
certificate keys in TLS 1.3. See RFC 8446, Section 4.4.3.
func skipUint16LengthPrefixed(s *cryptobyte.String) bool
func skipUint8LengthPrefixed(s *cryptobyte.String) bool
func sliceForAppend(in []byte, n int) (head, tail []byte)
sliceForAppend extends the input slice by n bytes. head is the full extended
slice, while tail is the appended part. If the original slice has sufficient
capacity no allocation is performed.
func splitPreMasterSecret(secret []byte) (s1, s2 []byte)
Split a premaster secret in two as specified in RFC 4346, Section 5.
func supportedVersionsFromMax(maxVersion uint16) []uint16
supportedVersionsFromMax returns a list of supported versions derived from
a legacy maximum version value. Note that only versions supported by this
library are returned. Any newer peer will use supportedVersions anyway.
func supportsECDHE(c *Config, version uint16, supportedCurves []CurveID, supportedPoints []uint8) bool
supportsECDHE returns whether ECDHE key exchanges can be used with this
pre-TLS 1.3 client.
func tls10MAC(h hash.Hash, out, seq, header, data, extra []byte) []byte
tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3.
func transcriptMsg(msg handshakeMessage, h transcriptHash) error
transcriptMsg is a helper used to hash messages which are not hashed when
they are read from, or written to, the wire. This is typically the case for
messages which are either not sent, or need to be hashed out of order from
when they are read/written.
For most messages, the message is marshalled using their marshal method,
since their wire representation is idempotent. For clientHelloMsg and
serverHelloMsg, we store the original wire representation of the message
and use that for hashing, since unmarshal/marshal are not idempotent due to
extension ordering and other malleable fields, which may cause differences
between what was received and what we marshal.
func typeAndHashFromSignatureScheme(signatureAlgorithm SignatureScheme) (sigType uint8, hash crypto.Hash, err error)
typeAndHashFromSignatureScheme returns the corresponding signature type and
crypto.Hash for a given TLS SignatureScheme.
func unexpectedMessageError(wanted, got any) error
func unmarshalCertificate(s *cryptobyte.String, certificate *Certificate) bool
func unsupportedCertificateError(cert *Certificate) error
unsupportedCertificateError returns a helpful error for certificates with an
unsupported private key.
func validDNSName(name string) bool
validDNSName is a rather rudimentary check for the validity of a DNS name.
This is used to check if the public_name in a ECHConfig is valid when we
are picking a config. This can be somewhat lax because even if we pick a
valid-looking name, the DNS layer will later reject it anyway.
func verifyHandshakeSignature(sigType uint8, pubkey crypto.PublicKey, hashFunc crypto.Hash, signed, sig []byte) error
verifyHandshakeSignature verifies a signature against pre-hashed (if
required) handshake contents.
TYPES
type AlertError uint8
An AlertError is a TLS alert.
When using a QUIC transport, QUICConn methods will return an error which
wraps AlertError rather than sending a TLS alert.
func (e AlertError) Error() string
type Certificate struct {
Certificate [][]byte
PrivateKey crypto.PrivateKey
SupportedSignatureAlgorithms []SignatureScheme
OCSPStaple []byte
SignedCertificateTimestamps [][]byte
Leaf *x509.Certificate
}
A Certificate is a chain of one or more certificates, leaf first.
func LoadX509KeyPair(certFile, keyFile string) (Certificate, error)
LoadX509KeyPair reads and parses a public/private key pair from a pair of
files. The files must contain PEM encoded data. The certificate file may
contain intermediate certificates following the leaf certificate to form a
certificate chain. On successful return, Certificate.Leaf will be populated.
Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was
discarded. This behavior can be re-enabled by setting "x509keypairleaf=0" in
the GODEBUG environment variable.
func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)
X509KeyPair parses a public/private key pair from a pair of PEM encoded
data. On successful return, Certificate.Leaf will be populated.
Before Go 1.23 Certificate.Leaf was left nil, and the parsed certificate was
discarded. This behavior can be re-enabled by setting "x509keypairleaf=0" in
the GODEBUG environment variable.
func (c *Certificate) leaf() (*x509.Certificate, error)
leaf returns the parsed leaf certificate, either from c.Leaf or by parsing
the corresponding c.Certificate[0].
type CertificateRequestInfo struct {
AcceptableCAs [][]byte
SignatureSchemes []SignatureScheme
Version uint16
ctx context.Context
}
CertificateRequestInfo contains information from a server's
CertificateRequest message, which is used to demand a certificate and proof
of control from a client.
func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo
certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
<= 1.2 CertificateRequest, making an effort to fill in missing information.
func (c *CertificateRequestInfo) Context() context.Context
Context returns the context of the handshake that is in progress.
This context is a child of the context passed to HandshakeContext, if any,
and is canceled when the handshake concludes.
func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error
SupportsCertificate returns nil if the provided certificate is supported by
the server that sent the CertificateRequest. Otherwise, it returns an error
describing the reason for the incompatibility.
type CertificateVerificationError struct {
UnverifiedCertificates []*x509.Certificate
Err error
}
CertificateVerificationError is returned when certificate verification fails
during the handshake.
func (e *CertificateVerificationError) Error() string
func (e *CertificateVerificationError) Unwrap() error
type CipherSuite struct {
ID uint16
Name string
SupportedVersions []uint16
Insecure bool
}
CipherSuite is a TLS cipher suite. Note that most functions in this package
accept and expose cipher suite IDs instead of this type.
func CipherSuites() []*CipherSuite
CipherSuites returns a list of cipher suites currently implemented by
this package, excluding those with security issues, which are returned by
InsecureCipherSuites.
The list is sorted by ID. Note that the default cipher suites selected by
this package might depend on logic that can't be captured by a static list,
and might not match those returned by this function.
func InsecureCipherSuites() []*CipherSuite
InsecureCipherSuites returns a list of cipher suites currently implemented
by this package and which have security issues.
Most applications should not use the cipher suites in this list, and should
only use those returned by CipherSuites.
type ClientAuthType int
ClientAuthType declares the policy the server will follow for TLS Client
Authentication.
const (
NoClientCert ClientAuthType = iota
RequestClientCert
RequireAnyClientCert
VerifyClientCertIfGiven
RequireAndVerifyClientCert
)
func (i ClientAuthType) String() string
type ClientHelloInfo struct {
CipherSuites []uint16
ServerName string
SupportedCurves []CurveID
SupportedPoints []uint8
SignatureSchemes []SignatureScheme
SupportedProtos []string
SupportedVersions []uint16
Extensions []uint16
Conn net.Conn
config *Config
ctx context.Context
}
ClientHelloInfo contains information from a ClientHello message in order
to guide application logic in the GetCertificate and GetConfigForClient
callbacks.
func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo
func (c *ClientHelloInfo) Context() context.Context
Context returns the context of the handshake that is in progress.
This context is a child of the context passed to HandshakeContext, if any,
and is canceled when the handshake concludes.
func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error
SupportsCertificate returns nil if the provided certificate is supported
by the client that sent the ClientHello. Otherwise, it returns an error
describing the reason for the incompatibility.
If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate
callback, this method will take into account the associated Config.
Note that if GetConfigForClient returns a different Config, the change can't
be accounted for by this method.
This function will call x509.ParseCertificate unless c.Leaf is set, which
can incur a significant performance cost.
type ClientSessionCache interface {
Get(sessionKey string) (session *ClientSessionState, ok bool)
Put(sessionKey string, cs *ClientSessionState)
}
ClientSessionCache is a cache of ClientSessionState objects that can be used
by a client to resume a TLS session with a given server. ClientSessionCache
implementations should expect to be called concurrently from different
goroutines. Up to TLS 1.2, only ticket-based resumption is supported,
not SessionID-based resumption. In TLS 1.3 they were merged into PSK modes,
which are supported via this interface.
func NewLRUClientSessionCache(capacity int) ClientSessionCache
NewLRUClientSessionCache returns a ClientSessionCache with the given
capacity that uses an LRU strategy. If capacity is < 1, a default capacity
is used instead.
type ClientSessionState struct {
session *SessionState
}
ClientSessionState contains the state needed by a client to resume a
previous TLS session.
func NewResumptionState(ticket []byte, state *SessionState) (*ClientSessionState, error)
NewResumptionState returns a state value that can be returned by
[ClientSessionCache.Get] to resume a previous session.
state needs to be returned by ParseSessionState, and the ticket and session
state must have been returned by ClientSessionState.ResumptionState.
func (cs *ClientSessionState) ResumptionState() (ticket []byte, state *SessionState, err error)
ResumptionState returns the session ticket sent by the server (also known as
the session's identity) and the state necessary to resume this session.
It can be called by [ClientSessionCache.Put] to serialize (with
SessionState.Bytes) and store the session.
type Config struct {
Rand io.Reader
Time func() time.Time
Certificates []Certificate
NameToCertificate map[string]*Certificate
GetCertificate func(*ClientHelloInfo) (*Certificate, error)
GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error)
GetConfigForClient func(*ClientHelloInfo) (*Config, error)
VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
VerifyConnection func(ConnectionState) error
RootCAs *x509.CertPool
NextProtos []string
ServerName string
ClientAuth ClientAuthType
ClientCAs *x509.CertPool
InsecureSkipVerify bool
CipherSuites []uint16
PreferServerCipherSuites bool
SessionTicketsDisabled bool
SessionTicketKey [32]byte
ClientSessionCache ClientSessionCache
UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error)
WrapSession func(ConnectionState, *SessionState) ([]byte, error)
MinVersion uint16
MaxVersion uint16
CurvePreferences []CurveID
DynamicRecordSizingDisabled bool
Renegotiation RenegotiationSupport
KeyLogWriter io.Writer
EncryptedClientHelloConfigList []byte
EncryptedClientHelloRejectionVerify func(ConnectionState) error
EncryptedClientHelloKeys []EncryptedClientHelloKey
mutex sync.RWMutex
sessionTicketKeys []ticketKey
autoSessionTicketKeys []ticketKey
}
A Config structure is used to configure a TLS client or server. After one
has been passed to a TLS function it must not be modified. A Config may be
reused; the tls package will also not modify it.
var emptyConfig Config
func defaultConfig() *Config
func (c *Config) BuildNameToCertificate()
BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
from the CommonName and SubjectAlternateName fields of each of the leaf
certificates.
Deprecated: NameToCertificate only allows associating a single certificate
with a given name. Leave that field nil to let the library select the first
compatible chain from Certificates.
func (c *Config) Clone() *Config
Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a
Config that is being used concurrently by a TLS client or server.
func (c *Config) DecryptTicket(identity []byte, cs ConnectionState) (*SessionState, error)
DecryptTicket decrypts a ticket encrypted by Config.EncryptTicket. It can be
used as a [Config.UnwrapSession] implementation.
If the ticket can't be decrypted or parsed, DecryptTicket returns (nil,
nil).
func (c *Config) EncryptTicket(cs ConnectionState, ss *SessionState) ([]byte, error)
EncryptTicket encrypts a ticket with the Config's configured (or
default) session ticket keys. It can be used as a [Config.WrapSession]
implementation.
func (c *Config) SetSessionTicketKeys(keys [][32]byte)
SetSessionTicketKeys updates the session ticket keys for a server.
The first key will be used when creating new tickets, while all keys can
be used for decrypting tickets. It is safe to call this function while the
server is running in order to rotate the session ticket keys. The function
will panic if keys is empty.
Calling this function will turn off automatic session ticket key rotation.
If multiple servers are terminating connections for the same host they
should all have the same session ticket keys. If the session ticket keys
leaks, previously recorded and future TLS connections using those keys might
be compromised.
func (c *Config) cipherSuites() []uint16
func (c *Config) curvePreferences(version uint16) []CurveID
func (c *Config) decryptTicket(encrypted []byte, ticketKeys []ticketKey) []byte
func (c *Config) encryptTicket(state []byte, ticketKeys []ticketKey) ([]byte, error)
func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error)
getCertificate returns the best certificate for the given ClientHelloInfo,
defaulting to the first element of c.Certificates.
func (c *Config) initLegacySessionTicketKeyRLocked()
initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field
is randomized if empty, and that sessionTicketKeys is populated from it
otherwise.
func (c *Config) maxSupportedVersion(isClient bool) uint16
func (c *Config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool)
mutualVersion returns the protocol version to use given the advertised
versions of the peer. Priority is given to the peer preference order.
func (c *Config) rand() io.Reader
func (c *Config) supportedVersions(isClient bool) []uint16
func (c *Config) supportsCurve(version uint16, curve CurveID) bool
func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey)
ticketKeyFromBytes converts from the external representation of a session
ticket key to a ticketKey. Externally, session ticket keys are 32 random
bytes and this function expands that into sufficient name and key material.
func (c *Config) ticketKeys(configForClient *Config) []ticketKey
ticketKeys returns the ticketKeys for this connection. If configForClient
has explicitly set keys, those will be returned. Otherwise, the keys
on c will be used and may be rotated if auto-managed. During rotation,
any expired session ticket keys are deleted from c.sessionTicketKeys.
If the session ticket key that is currently encrypting tickets (ie.
the first ticketKey in c.sessionTicketKeys) is not fresh, then a new session
ticket key will be created and prepended to c.sessionTicketKeys.
func (c *Config) time() time.Time
func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error
type Conn struct {
conn net.Conn
isClient bool
isHandshakeComplete atomic.Bool
handshakeMutex sync.Mutex
handshakes int
extMasterSecret bool
cipherSuite uint16
curveID CurveID
peerCertificates []*x509.Certificate
activeCertHandles []*activeCert
verifiedChains [][]*x509.Certificate
serverName string
secureRenegotiation bool
ekm func(label string, context []byte, length int) ([]byte, error)
resumptionSecret []byte
echAccepted bool
ticketKeys []ticketKey
clientFinishedIsFirst bool
closeNotifyErr error
closeNotifySent bool
clientFinished [12]byte
serverFinished [12]byte
clientProtocol string
in, out halfConn
bytesSent int64
packetsSent int64
retryCount int
activeCall atomic.Int32
tmp [16]byte
}
A Conn represents a secured connection. It implements the net.Conn
interface.
func Client(conn net.Conn, config *Config) *Conn
Client returns a new TLS client side connection using conn as the underlying
transport. The config cannot be nil: users must set either ServerName or
InsecureSkipVerify in the config.
func Dial(network, addr string, config *Config) (*Conn, error)
Dial connects to the given network address using net.Dial and then
initiates a TLS handshake, returning the resulting TLS connection.
Dial interprets a nil configuration as equivalent to the zero configuration;
see the documentation of Config for the defaults.
func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)
DialWithDialer connects to the given network address using dialer.Dial and
then initiates a TLS handshake, returning the resulting TLS connection.
Any timeout or deadline given in the dialer apply to connection and TLS
handshake as a whole.
DialWithDialer interprets a nil configuration as equivalent to the zero
configuration; see the documentation of Config for the defaults.
DialWithDialer uses context.Background internally; to specify the context,
use Dialer.DialContext with NetDialer set to the desired dialer.
func Server(conn net.Conn, config *Config) *Conn
Server returns a new TLS server side connection using conn as the underlying
transport. The configuration config must be non-nil and must include at
least one certificate or else set GetCertificate.
func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error)
func (c *Conn) Close() error
Close closes the connection.
func (c *Conn) CloseWrite() error
CloseWrite shuts down the writing side of the connection. It should only be
called once the handshake has completed and does not call CloseWrite on the
underlying connection. Most callers should just use Conn.Close.
func (c *Conn) ConnectionState() ConnectionState
ConnectionState returns basic TLS details about the connection.
func (c *Conn) Handshake() error
Handshake runs the client or server handshake protocol if it has not yet
been run.
Most uses of this package need not call Handshake explicitly: the first
Conn.Read or Conn.Write will call it automatically.
For control over canceling or setting a timeout on a handshake, use
Conn.HandshakeContext or the Dialer's DialContext method instead.
In order to avoid denial of service attacks, the maximum RSA key size
allowed in certificates sent by either the TLS server or client is limited
to 8192 bits. This limit can be overridden by setting tlsmaxrsasize in the
GODEBUG environment variable (e.g. GODEBUG=tlsmaxrsasize=4096).
func (c *Conn) HandshakeContext(ctx context.Context) error
HandshakeContext runs the client or server handshake protocol if it has not
yet been run.
The provided Context must be non-nil. If the context is canceled before
the handshake is complete, the handshake is interrupted and an error is
returned. Once the handshake has completed, cancellation of the context will
not affect the connection.
Most uses of this package need not call HandshakeContext explicitly:
the first Conn.Read or Conn.Write will call it automatically.
func (c *Conn) LocalAddr() net.Addr
LocalAddr returns the local network address.
func (c *Conn) NetConn() net.Conn
NetConn returns the underlying connection that is wrapped by c. Note that
writing to or reading from this connection directly will corrupt the TLS
session.
func (c *Conn) OCSPResponse() []byte
OCSPResponse returns the stapled OCSP response from the TLS server, if any.
(Only valid for client connections.)
func (c *Conn) Read(b []byte) (int, error)
Read reads data from the connection.
As Read calls Conn.Handshake, in order to prevent indefinite blocking
a deadline must be set for both Read and Conn.Write before Read is
called when the handshake has not yet completed. See Conn.SetDeadline,
Conn.SetReadDeadline, and Conn.SetWriteDeadline.
func (c *Conn) RemoteAddr() net.Addr
RemoteAddr returns the remote network address.
func (c *Conn) SetDeadline(t time.Time) error
SetDeadline sets the read and write deadlines associated with the
connection. A zero value for t means Conn.Read and Conn.Write will not time
out. After a Write has timed out, the TLS state is corrupt and all future
writes will return the same error.
func (c *Conn) SetReadDeadline(t time.Time) error
SetReadDeadline sets the read deadline on the underlying connection.
A zero value for t means Conn.Read will not time out.
func (c *Conn) SetWriteDeadline(t time.Time) error
SetWriteDeadline sets the write deadline on the underlying connection.
A zero value for t means Conn.Write will not time out. After a Conn.Write
has timed out, the TLS state is corrupt and all future writes will return
the same error.
func (c *Conn) VerifyHostname(host string) error
VerifyHostname checks that the peer certificate chain is valid for
connecting to host. If so, it returns nil; if not, it returns an error
describing the problem.
func (c *Conn) Write(b []byte) (int, error)
Write writes data to the connection.
As Write calls Conn.Handshake, in order to prevent indefinite blocking
a deadline must be set for both Conn.Read and Write before Write is
called when the handshake has not yet completed. See Conn.SetDeadline,
Conn.SetReadDeadline, and Conn.SetWriteDeadline.
func (c *Conn) clientHandshake(ctx context.Context) (err error)
func (c *Conn) clientSessionCacheKey() string
clientSessionCacheKey returns a key used to cache sessionTickets that could
be used to resume previously negotiated TLS sessions with a server.
func (c *Conn) closeNotify() error
func (c *Conn) connectionStateLocked() ConnectionState
func (c *Conn) flush() (int, error)
func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error)
func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error
func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error
func (c *Conn) handlePostHandshakeMessage() error
handlePostHandshakeMessage processes a handshake message arrived after
the handshake is complete. Up to TLS 1.2, it indicates the start of a
renegotiation.
func (c *Conn) handleRenegotiation() error
handleRenegotiation processes a HelloRequest handshake message.
func (c *Conn) handshakeContext(ctx context.Context) (ret error)
func (c *Conn) loadSession(hello *clientHelloMsg) (
session *SessionState, earlySecret *tls13.EarlySecret, binderKey []byte, err error)
func (c *Conn) makeClientHello() (*clientHelloMsg, *keySharePrivateKeys, *echClientContext, error)
func (c *Conn) maxPayloadSizeForWrite(typ recordType) int
maxPayloadSizeForWrite returns the maximum TLS payload size to use for the
next application data record. There is the following trade-off:
- For latency-sensitive applications, such as web browsing, each TLS
record should fit in one TCP segment.
- For throughput-sensitive applications, such as large file transfers,
larger TLS records better amortize framing and encryption overheads.
A simple heuristic that works well in practice is to use small records
for the first 1MB of data, then use larger records for subsequent data,
and reset back to smaller records after the connection becomes
idle. See "High Performance Web Networking", Chapter 4, or:
In the interests of simplicity and determinism, this code does not attempt
to reset the record size once the connection is idle, however.
func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError)
func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error
func (c *Conn) processCertsFromClient(certificate Certificate) error
processCertsFromClient takes a chain of client certificates either from a
Certificates message and verifies them.
func (c *Conn) processECHClientHello(outer *clientHelloMsg) (*clientHelloMsg, *echServerContext, error)
func (c *Conn) quicGetTransportParameters() ([]byte, error)
func (c *Conn) quicHandshakeComplete()
func (c *Conn) quicReadHandshakeBytes(n int) error
func (c *Conn) quicRejectedEarlyData()
func (c *Conn) quicResumeSession(session *SessionState) error
func (c *Conn) quicSetReadSecret(level QUICEncryptionLevel, suite uint16, secret []byte)
func (c *Conn) quicSetTransportParameters(params []byte)
func (c *Conn) quicSetWriteSecret(level QUICEncryptionLevel, suite uint16, secret []byte)
func (c *Conn) quicStoreSession(session *SessionState)
func (c *Conn) quicWaitForSignal() error
quicWaitForSignal notifies the QUICConn that handshake progress is blocked,
and waits for a signal that the handshake should proceed.
The handshake may become blocked waiting for handshake bytes or for the user
to provide transport parameters.
func (c *Conn) quicWriteCryptoData(level QUICEncryptionLevel, data []byte)
func (c *Conn) readChangeCipherSpec() error
func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, *echServerContext, error)
readClientHello reads a ClientHello message and selects the protocol
version.
func (c *Conn) readFromUntil(r io.Reader, n int) error
readFromUntil reads from r into c.rawInput until c.rawInput contains at
least n bytes or else returns an error.
func (c *Conn) readHandshake(transcript transcriptHash) (any, error)
readHandshake reads the next handshake message from the record layer. If
transcript is non-nil, the message is written to the passed transcriptHash.
func (c *Conn) readHandshakeBytes(n int) error
readHandshakeBytes reads handshake data until c.hand contains at least n
bytes.
func (c *Conn) readRecord() error
func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error
readRecordOrCCS reads one or more TLS records from the connection and
updates the record layer state. Some invariants:
- c.in must be locked
- c.input must be empty
During the handshake one and only one of the following will happen:
- c.hand grows
- c.in.changeCipherSpec is called
- an error is returned
After the handshake one and only one of the following will happen:
- c.hand grows
- c.input is set
- an error is returned
func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error
retryReadRecord recurs into readRecordOrCCS to drop a non-advancing record,
like a warning alert, empty application_data, or a change_cipher_spec in TLS
1.3.
func (c *Conn) sendAlert(err alert) error
sendAlert sends a TLS alert message.
func (c *Conn) sendAlertLocked(err alert) error
sendAlertLocked sends a TLS alert message.
func (c *Conn) sendSessionTicket(earlyData bool, extra [][]byte) error
func (c *Conn) serverHandshake(ctx context.Context) error
serverHandshake performs a TLS handshake as a server.
func (c *Conn) sessionState() *SessionState
sessionState returns a partially filled-out SessionState with information
from the current connection.
func (c *Conn) unmarshalHandshakeMessage(data []byte, transcript transcriptHash) (handshakeMessage, error)
func (c *Conn) verifyServerCertificate(certificates [][]byte) error
verifyServerCertificate parses and verifies the provided chain, setting
c.verifiedChains and c.peerCertificates or sending the appropriate alert.
func (c *Conn) write(data []byte) (int, error)
func (c *Conn) writeChangeCipherRecord() error
writeChangeCipherRecord writes a ChangeCipherSpec message to the connection
and updates the record layer state.
func (c *Conn) writeHandshakeRecord(msg handshakeMessage, transcript transcriptHash) (int, error)
writeHandshakeRecord writes a handshake message to the connection and
updates the record layer state. If transcript is non-nil the marshaled
message is written to it.
func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error)
writeRecordLocked writes a TLS record with the given type and payload to the
connection and updates the record layer state.
type ConnectionState struct {
Version uint16
HandshakeComplete bool
DidResume bool
CipherSuite uint16
NegotiatedProtocol string
NegotiatedProtocolIsMutual bool
ServerName string
PeerCertificates []*x509.Certificate
VerifiedChains [][]*x509.Certificate
SignedCertificateTimestamps [][]byte
OCSPResponse []byte
TLSUnique []byte
ECHAccepted bool
ekm func(label string, context []byte, length int) ([]byte, error)
testingOnlyDidHRR bool
testingOnlyCurveID CurveID
}
ConnectionState records basic TLS details about the connection.
func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)
ExportKeyingMaterial returns length bytes of exported key material in a
new slice as defined in RFC 5705. If context is nil, it is not used as
part of the seed. If the connection was set to allow renegotiation via
Config.Renegotiation, or if the connections supports neither TLS 1.3 nor
Extended Master Secret, this function will return an error.
Exporting key material without Extended Master Secret or TLS 1.3 was
disabled in Go 1.22 due to security issues (see the Security Considerations
sections of RFC 5705 and RFC 7627), but can be re-enabled with the GODEBUG
setting tlsunsafeekm=1.
type CurveID uint16
CurveID is the type of a TLS identifier for a key exchange mechanism. See
In TLS 1.2, this registry used to support only elliptic curves. In TLS 1.3,
it was extended to other groups and renamed NamedGroup. See RFC 8446,
Section 4.2.7. It was then also extended to other mechanisms, such as hybrid
post-quantum KEMs.
const (
CurveP256 CurveID = 23
CurveP384 CurveID = 24
CurveP521 CurveID = 25
X25519 CurveID = 29
X25519MLKEM768 CurveID = 4588
)
func defaultCurvePreferences() []CurveID
defaultCurvePreferences is the default set of supported key exchanges,
as well as the preference order.
func (i CurveID) String() string
type Dialer struct {
NetDialer *net.Dialer
Config *Config
}
Dialer dials TLS connections given a configuration and a Dialer for the
underlying connection.
func (d *Dialer) Dial(network, addr string) (net.Conn, error)
Dial connects to the given network address and initiates a TLS handshake,
returning the resulting TLS connection.
The returned Conn, if any, will always be of type *Conn.
Dial uses context.Background internally; to specify the context, use
Dialer.DialContext.
func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)
DialContext connects to the given network address and initiates a TLS
handshake, returning the resulting TLS connection.
The provided Context must be non-nil. If the context expires before the
connection is complete, an error is returned. Once successfully connected,
any expiration of the context will not affect the connection.
The returned Conn, if any, will always be of type *Conn.
func (d *Dialer) netDialer() *net.Dialer
type ECHRejectionError struct {
RetryConfigList []byte
}
ECHRejectionError is the error type returned when ECH is rejected by a
remote server. If the server offered a ECHConfigList to use for retries,
the RetryConfigList field will contain this list.
The client may treat an ECHRejectionError with an empty set of RetryConfigs
as a secure signal from the server.
func (e *ECHRejectionError) Error() string
type EncryptedClientHelloKey struct {
Config []byte
PrivateKey []byte
SendAsRetry bool
}
EncryptedClientHelloKey holds a private key that is associated with a
specific ECH config known to a client.
type QUICConfig struct {
TLSConfig *Config
EnableSessionEvents bool
}
A QUICConfig configures a QUICConn.
type QUICConn struct {
conn *Conn
sessionTicketSent bool
}
A QUICConn represents a connection which uses a QUIC implementation as the
underlying transport as described in RFC 9001.
Methods of QUICConn are not safe for concurrent use.
func QUICClient(config *QUICConfig) *QUICConn
QUICClient returns a new TLS client side connection using QUICTransport as
the underlying transport. The config cannot be nil.
The config's MinVersion must be at least TLS 1.3.
func QUICServer(config *QUICConfig) *QUICConn
QUICServer returns a new TLS server side connection using QUICTransport as
the underlying transport. The config cannot be nil.
The config's MinVersion must be at least TLS 1.3.
func newQUICConn(conn *Conn, config *QUICConfig) *QUICConn
func (q *QUICConn) Close() error
Close closes the connection and stops any in-progress handshake.
func (q *QUICConn) ConnectionState() ConnectionState
ConnectionState returns basic TLS details about the connection.
func (q *QUICConn) HandleData(level QUICEncryptionLevel, data []byte) error
HandleData handles handshake bytes received from the peer. It may produce
connection events, which may be read with QUICConn.NextEvent.
func (q *QUICConn) NextEvent() QUICEvent
NextEvent returns the next event occurring on the connection. It returns an
event with a Kind of QUICNoEvent when no events are available.
func (q *QUICConn) SendSessionTicket(opts QUICSessionTicketOptions) error
SendSessionTicket sends a session ticket to the client. It produces
connection events, which may be read with QUICConn.NextEvent. Currently,
it can only be called once.
func (q *QUICConn) SetTransportParameters(params []byte)
SetTransportParameters sets the transport parameters to send to the peer.
Server connections may delay setting the transport parameters
until after receiving the client's transport parameters. See
QUICTransportParametersRequired.
func (q *QUICConn) Start(ctx context.Context) error
Start starts the client or server handshake protocol. It may produce
connection events, which may be read with QUICConn.NextEvent.
Start must be called at most once.
func (q *QUICConn) StoreSession(session *SessionState) error
StoreSession stores a session previously received in a QUICStoreSession
event in the ClientSessionCache. The application may process additional
events or modify the SessionState before storing the session.
type QUICEncryptionLevel int
QUICEncryptionLevel represents a QUIC encryption level used to transmit
handshake messages.
func (l QUICEncryptionLevel) String() string
type QUICEvent struct {
Kind QUICEventKind
Level QUICEncryptionLevel
Data []byte
Suite uint16
SessionState *SessionState
}
A QUICEvent is an event occurring on a QUIC connection.
The type of event is specified by the Kind field. The contents of the other
fields are kind-specific.
type QUICEventKind int
A QUICEventKind is a type of operation on a QUIC connection.
const (
QUICNoEvent QUICEventKind = iota
QUICSetReadSecret
QUICSetWriteSecret
QUICWriteData
QUICTransportParameters
QUICTransportParametersRequired
QUICRejectedEarlyData
QUICHandshakeDone
QUICResumeSession
QUICStoreSession
)
type QUICSessionTicketOptions struct {
EarlyData bool
Extra [][]byte
}
type RecordHeaderError struct {
Msg string
RecordHeader [5]byte
Conn net.Conn
}
RecordHeaderError is returned when a TLS record header is invalid.
func (e RecordHeaderError) Error() string
type RenegotiationSupport int
RenegotiationSupport enumerates the different levels of support for TLS
renegotiation. TLS renegotiation is the act of performing subsequent
handshakes on a connection after the first. This significantly complicates
the state machine and has been the source of numerous, subtle security
issues. Initiating a renegotiation is not supported, but support for
accepting renegotiation requests may be enabled.
Even when enabled, the server may not change its identity between handshakes
(i.e. the leaf certificate must be the same). Additionally, concurrent
handshake and application data flow is not permitted so renegotiation
can only be used with protocols that synchronise with the renegotiation,
such as HTTPS.
Renegotiation is not defined in TLS 1.3.
const (
RenegotiateNever RenegotiationSupport = iota
RenegotiateOnceAsClient
RenegotiateFreelyAsClient
)
type SessionState struct {
Extra [][]byte
EarlyData bool
version uint16
isClient bool
cipherSuite uint16
extMasterSecret bool
peerCertificates []*x509.Certificate
activeCertHandles []*activeCert
ocspResponse []byte
scts [][]byte
verifiedChains [][]*x509.Certificate
ageAdd uint32
ticket []byte
}
A SessionState is a resumable session.
func ParseSessionState(data []byte) (*SessionState, error)
ParseSessionState parses a SessionState encoded by SessionState.Bytes.
func (s *SessionState) Bytes() ([]byte, error)
Bytes encodes the session, including any private fields, so that it can be
parsed by ParseSessionState. The encoding contains secret values critical to
the security of future and possibly past sessions.
The specific encoding should be considered opaque and may change
incompatibly between Go versions.
type SignatureScheme uint16
SignatureScheme identifies a signature algorithm supported by TLS. See RFC
8446, Section 4.2.3.
const (
PKCS1WithSHA256 SignatureScheme = 0x0401
PKCS1WithSHA384 SignatureScheme = 0x0501
PKCS1WithSHA512 SignatureScheme = 0x0601
PSSWithSHA256 SignatureScheme = 0x0804
PSSWithSHA384 SignatureScheme = 0x0805
PSSWithSHA512 SignatureScheme = 0x0806
ECDSAWithP256AndSHA256 SignatureScheme = 0x0403
ECDSAWithP384AndSHA384 SignatureScheme = 0x0503
ECDSAWithP521AndSHA512 SignatureScheme = 0x0603
Ed25519 SignatureScheme = 0x0807
PKCS1WithSHA1 SignatureScheme = 0x0201
ECDSAWithSHA1 SignatureScheme = 0x0203
)
func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error)
selectSignatureScheme picks a SignatureScheme from the peer's preference
list that works with the selected certificate. It's only called for protocol
versions that support signature algorithms, so TLS 1.2 and 1.3.
func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme
signatureSchemesForCertificate returns the list of supported
SignatureSchemes for a given certificate, based on the public key
and the protocol version, and optionally filtered by its explicit
SupportedSignatureAlgorithms.
This function must be kept in sync with supportedSignatureAlgorithms.
FIPS filtering is applied in the caller, selectSignatureScheme.
func supportedSignatureAlgorithms() []SignatureScheme
supportedSignatureAlgorithms returns the supported signature algorithms.
func (i SignatureScheme) String() string
type activeCert struct {
cert *x509.Certificate
}
activeCert is a handle to a certificate held in the cache. Once there are no
alive activeCerts for a given certificate, the certificate is removed from
the cache by a finalizer.
type aead interface {
cipher.AEAD
explicitNonceLen() int
}
func aeadAESGCM(key, noncePrefix []byte) aead
func aeadAESGCMTLS13(key, nonceMask []byte) aead
aeadAESGCMTLS13 should be an internal detail, but widely used packages
access it using linkname. Notable members of the hall of shame include:
- github.com/xtls/xray-core
- github.com/v2fly/v2ray-core
Do not remove or change the type signature. See go.dev/issue/67401.
func aeadChaCha20Poly1305(key, nonceMask []byte) aead
type alert uint8
const (
alertCloseNotify alert = 0
alertUnexpectedMessage alert = 10
alertBadRecordMAC alert = 20
alertDecryptionFailed alert = 21
alertRecordOverflow alert = 22
alertDecompressionFailure alert = 30
alertHandshakeFailure alert = 40
alertBadCertificate alert = 42
alertUnsupportedCertificate alert = 43
alertCertificateRevoked alert = 44
alertCertificateExpired alert = 45
alertCertificateUnknown alert = 46
alertIllegalParameter alert = 47
alertUnknownCA alert = 48
alertAccessDenied alert = 49
alertDecodeError alert = 50
alertDecryptError alert = 51
alertExportRestriction alert = 60
alertProtocolVersion alert = 70
alertInsufficientSecurity alert = 71
alertInternalError alert = 80
alertInappropriateFallback alert = 86
alertUserCanceled alert = 90
alertNoRenegotiation alert = 100
alertMissingExtension alert = 109
alertUnsupportedExtension alert = 110
alertCertificateUnobtainable alert = 111
alertUnrecognizedName alert = 112
alertBadCertificateStatusResponse alert = 113
alertBadCertificateHashValue alert = 114
alertUnknownPSKIdentity alert = 115
alertCertificateRequired alert = 116
alertNoApplicationProtocol alert = 120
alertECHRequired alert = 121
)
func (e alert) Error() string
func (e alert) String() string
type atLeastReader struct {
R io.Reader
N int64
}
atLeastReader reads from R, stopping with EOF once at least N bytes have
been read. It is different from an io.LimitedReader in that it doesn't cut
short the last Read call, and in that it considers an early EOF an error.
func (r *atLeastReader) Read(p []byte) (int, error)
type cacheEntry struct {
refs atomic.Int64
cert *x509.Certificate
}
type cbcMode interface {
cipher.BlockMode
SetIV([]byte)
}
cbcMode is an interface for block ciphers using cipher block chaining.
type certCache struct {
sync.Map
}
certCache implements an intern table for reference counted
x509.Certificates, implemented in a similar fashion to BoringSSL's
CRYPTO_BUFFER_POOL. This allows for a single x509.Certificate to be kept in
memory and referenced from multiple Conns. Returned references should not
be mutated by callers. Certificates are still safe to use after they are
removed from the cache.
Certificates are returned wrapped in an activeCert struct that should be
held by the caller. When references to the activeCert are freed, the number
of references to the certificate in the cache is decremented. Once the
number of references reaches zero, the entry is evicted from the cache.
The main difference between this implementation and CRYPTO_BUFFER_POOL
is that CRYPTO_BUFFER_POOL is a more generic structure which supports
blobs of data, rather than specific structures. Since we only care about
x509.Certificates, certCache is implemented as a specific cache, rather than
a generic one.
See
for the BoringSSL reference.
func (cc *certCache) active(e *cacheEntry) *activeCert
active increments the number of references to the entry, wraps the
certificate in the entry in an activeCert, and sets the finalizer.
Note that there is a race between active and the finalizer set on the
returned activeCert, triggered if active is called after the ref count is
decremented such that refs may be > 0 when evict is called. We consider this
safe, since the caller holding an activeCert for an entry that is no longer
in the cache is fine, with the only side effect being the memory overhead of
there being more than one distinct reference to a certificate alive at once.
func (cc *certCache) evict(e *cacheEntry)
evict removes a cacheEntry from the cache.
func (cc *certCache) newCert(der []byte) (*activeCert, error)
newCert returns a x509.Certificate parsed from der. If there is already
a copy of the certificate in the cache, a reference to the existing
certificate will be returned. Otherwise, a fresh certificate will be added
to the cache, and the reference returned. The returned reference should not
be mutated.
type certificateMsg struct {
certificates [][]byte
}
func (m *certificateMsg) marshal() ([]byte, error)
func (m *certificateMsg) unmarshal(data []byte) bool
type certificateMsgTLS13 struct {
certificate Certificate
ocspStapling bool
scts bool
}
func (m *certificateMsgTLS13) marshal() ([]byte, error)
func (m *certificateMsgTLS13) unmarshal(data []byte) bool
type certificateRequestMsg struct {
hasSignatureAlgorithm bool
certificateTypes []byte
supportedSignatureAlgorithms []SignatureScheme
certificateAuthorities [][]byte
}
func (m *certificateRequestMsg) marshal() ([]byte, error)
func (m *certificateRequestMsg) unmarshal(data []byte) bool
type certificateRequestMsgTLS13 struct {
ocspStapling bool
scts bool
supportedSignatureAlgorithms []SignatureScheme
supportedSignatureAlgorithmsCert []SignatureScheme
certificateAuthorities [][]byte
}
func (m *certificateRequestMsgTLS13) marshal() ([]byte, error)
func (m *certificateRequestMsgTLS13) unmarshal(data []byte) bool
type certificateStatusMsg struct {
response []byte
}
func (m *certificateStatusMsg) marshal() ([]byte, error)
func (m *certificateStatusMsg) unmarshal(data []byte) bool
type certificateVerifyMsg struct {
signatureAlgorithm SignatureScheme
signature []byte
}
func (m *certificateVerifyMsg) marshal() ([]byte, error)
func (m *certificateVerifyMsg) unmarshal(data []byte) bool
type cipherSuite struct {
id uint16
keyLen int
macLen int
ivLen int
ka func(version uint16) keyAgreement
flags int
cipher func(key, iv []byte, isRead bool) any
mac func(key []byte) hash.Hash
aead func(key, fixedNonce []byte) aead
}
A cipherSuite is a TLS 1.0–1.2 cipher suite, and defines the key exchange
mechanism, as well as the cipher+MAC pair or the AEAD.
func cipherSuiteByID(id uint16) *cipherSuite
func mutualCipherSuite(have []uint16, want uint16) *cipherSuite
mutualCipherSuite returns a cipherSuite given a list of supported
ciphersuites and the id requested by the peer.
func selectCipherSuite(ids, supportedIDs []uint16, ok func(*cipherSuite) bool) *cipherSuite
selectCipherSuite returns the first TLS 1.0–1.2 cipher suite from ids which
is also in supportedIDs and passes the ok filter.
type cipherSuiteTLS13 struct {
id uint16
keyLen int
aead func(key, fixedNonce []byte) aead
hash crypto.Hash
}
A cipherSuiteTLS13 defines only the pair of the AEAD algorithm and hash
algorithm to be used with HKDF. See RFC 8446, Appendix B.4.
func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13
func mutualCipherSuiteTLS13(have []uint16, want uint16) *cipherSuiteTLS13
func (c *cipherSuiteTLS13) exportKeyingMaterial(s *tls13.MasterSecret, transcript hash.Hash) func(string, []byte, int) ([]byte, error)
exportKeyingMaterial implements RFC5705 exporters for TLS 1.3 according to
RFC 8446, Section 7.5.
func (c *cipherSuiteTLS13) finishedHash(baseKey []byte, transcript hash.Hash) []byte
finishedHash generates the Finished verify_data or PskBinderEntry according
to RFC 8446, Section 4.4.4. See sections 4.4 and 4.2.11.2 for the baseKey
selection.
func (c *cipherSuiteTLS13) nextTrafficSecret(trafficSecret []byte) []byte
nextTrafficSecret generates the next traffic secret, given the current one,
according to RFC 8446, Section 7.2.
func (c *cipherSuiteTLS13) trafficKey(trafficSecret []byte) (key, iv []byte)
trafficKey generates traffic keys according to RFC 8446, Section 7.3.
type clientHandshakeState struct {
c *Conn
ctx context.Context
serverHello *serverHelloMsg
hello *clientHelloMsg
suite *cipherSuite
finishedHash finishedHash
masterSecret []byte
}
func (hs *clientHandshakeState) doFullHandshake() error
func (hs *clientHandshakeState) establishKeys() error
func (hs *clientHandshakeState) handshake() error
Does the handshake, either a full one or resumes old session. Requires hs.c,
hs.hello, hs.serverHello, and, optionally, hs.session to be set.
func (hs *clientHandshakeState) pickCipherSuite() error
func (hs *clientHandshakeState) processServerHello() (bool, error)
func (hs *clientHandshakeState) readFinished(out []byte) error
func (hs *clientHandshakeState) readSessionTicket() error
func (hs *clientHandshakeState) saveSessionTicket() error
func (hs *clientHandshakeState) sendFinished(out []byte) error
func (hs *clientHandshakeState) serverResumedSession() bool
type clientHandshakeStateTLS13 struct {
c *Conn
ctx context.Context
serverHello *serverHelloMsg
hello *clientHelloMsg
keyShareKeys *keySharePrivateKeys
session *SessionState
earlySecret *tls13.EarlySecret
binderKey []byte
certReq *certificateRequestMsgTLS13
usingPSK bool
sentDummyCCS bool
suite *cipherSuiteTLS13
transcript hash.Hash
masterSecret *tls13.MasterSecret
echContext *echClientContext
}
func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error
checkServerHelloOrHRR does validity checks that apply to both ServerHello
and HelloRetryRequest messages. It sets hs.suite.
func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error
func (hs *clientHandshakeStateTLS13) handshake() error
handshake requires hs.c, hs.hello, hs.serverHello, hs.keyShareKeys, and,
optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error
processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
resends hs.hello, and reads the new ServerHello into hs.serverHello.
func (hs *clientHandshakeStateTLS13) processServerHello() error
func (hs *clientHandshakeStateTLS13) readServerCertificate() error
func (hs *clientHandshakeStateTLS13) readServerFinished() error
func (hs *clientHandshakeStateTLS13) readServerParameters() error
func (hs *clientHandshakeStateTLS13) sendClientCertificate() error
func (hs *clientHandshakeStateTLS13) sendClientFinished() error
func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error
sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix
D.4.
type clientHelloMsg struct {
original []byte
vers uint16
random []byte
sessionId []byte
cipherSuites []uint16
compressionMethods []uint8
serverName string
ocspStapling bool
supportedCurves []CurveID
supportedPoints []uint8
ticketSupported bool
sessionTicket []uint8
supportedSignatureAlgorithms []SignatureScheme
supportedSignatureAlgorithmsCert []SignatureScheme
secureRenegotiationSupported bool
secureRenegotiation []byte
extendedMasterSecret bool
alpnProtocols []string
scts bool
supportedVersions []uint16
cookie []byte
keyShares []keyShare
earlyData bool
pskModes []uint8
pskIdentities []pskIdentity
pskBinders [][]byte
quicTransportParameters []byte
encryptedClientHello []byte
extensions []uint16
}
func decodeInnerClientHello(outer *clientHelloMsg, encoded []byte) (*clientHelloMsg, error)
func (m *clientHelloMsg) clone() *clientHelloMsg
func (m *clientHelloMsg) marshal() ([]byte, error)
func (m *clientHelloMsg) marshalMsg(echInner bool) ([]byte, error)
func (m *clientHelloMsg) marshalWithoutBinders() ([]byte, error)
marshalWithoutBinders returns the ClientHello through the
PreSharedKeyExtension.identities field, according to RFC 8446, Section
4.2.11.2. Note that m.pskBinders must be set to slices of the correct
length.
func (m *clientHelloMsg) originalBytes() []byte
func (m *clientHelloMsg) unmarshal(data []byte) bool
func (m *clientHelloMsg) updateBinders(pskBinders [][]byte) error
updateBinders updates the m.pskBinders field. The supplied binders must have
the same length as the current m.pskBinders.
type clientKeyExchangeMsg struct {
ciphertext []byte
}
func (m *clientKeyExchangeMsg) marshal() ([]byte, error)
func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool
type constantTimeHash interface {
hash.Hash
ConstantTimeSum(b []byte) []byte
}
type cthWrapper struct {
h constantTimeHash
}
cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces
with that all calls to Sum. It's used to obtain a ConstantTimeSum-based
HMAC.
func (c *cthWrapper) BlockSize() int
func (c *cthWrapper) Reset()
func (c *cthWrapper) Size() int
func (c *cthWrapper) Sum(b []byte) []byte
func (c *cthWrapper) Write(p []byte) (int, error)
type ecdheKeyAgreement struct {
version uint16
isRSA bool
key *ecdh.PrivateKey
ckx *clientKeyExchangeMsg
preMasterSecret []byte
}
ecdheKeyAgreement implements a TLS key agreement where the server generates
an ephemeral EC public/private key pair and signs it. The pre-master secret
is then calculated using ECDH. The signature may be ECDSA, Ed25519 or RSA.
func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error)
func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error)
func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error
type echCipher struct {
KDFID uint16
AEADID uint16
}
func pickECHCipherSuite(suites []echCipher) (echCipher, error)
type echClientContext struct {
config *echConfig
hpkeContext *hpke.Sender
encapsulatedKey []byte
innerHello *clientHelloMsg
innerTranscript hash.Hash
kdfID uint16
aeadID uint16
echRejected bool
}
type echConfig struct {
raw []byte
Version uint16
Length uint16
ConfigID uint8
KemID uint16
PublicKey []byte
SymmetricCipherSuite []echCipher
MaxNameLength uint8
PublicName []byte
Extensions []echExtension
}
func parseECHConfigList(data []byte) ([]echConfig, error)
parseECHConfigList parses a draft-ietf-tls-esni-18 ECHConfigList,
returning a slice of parsed ECHConfigs, in the same order they were parsed,
or an error if the list is malformed.
func pickECHConfig(list []echConfig) *echConfig
type echExtType uint8
const (
innerECHExt echExtType = 1
outerECHExt echExtType = 0
)
type echExtension struct {
Type uint16
Data []byte
}
type echServerContext struct {
hpkeContext *hpke.Receipient
configID uint8
ciphersuite echCipher
transcript hash.Hash
inner bool
}
type encryptedExtensionsMsg struct {
alpnProtocol string
quicTransportParameters []byte
earlyData bool
echRetryConfigs []byte
}
func (m *encryptedExtensionsMsg) marshal() ([]byte, error)
func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool
type endOfEarlyDataMsg struct{}
func (m *endOfEarlyDataMsg) marshal() ([]byte, error)
func (m *endOfEarlyDataMsg) unmarshal(data []byte) bool
type finishedHash struct {
client hash.Hash
server hash.Hash
clientMD5 hash.Hash
serverMD5 hash.Hash
buffer []byte
version uint16
prf prfFunc
}
A finishedHash calculates the hash of a set of handshake messages suitable
for including in a Finished message.
func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash
func (h finishedHash) Sum() []byte
func (h *finishedHash) Write(msg []byte) (n int, err error)
func (h finishedHash) clientSum(masterSecret []byte) []byte
clientSum returns the contents of the verify_data member of a client's
Finished message.
func (h *finishedHash) discardHandshakeBuffer()
discardHandshakeBuffer is called when there is no more need to buffer the
entirety of the handshake messages.
func (h finishedHash) hashForClientCertificate(sigType uint8, hashAlg crypto.Hash) []byte
hashForClientCertificate returns the handshake messages so far, pre-hashed
if necessary, suitable for signing by a TLS client certificate.
func (h finishedHash) serverSum(masterSecret []byte) []byte
serverSum returns the contents of the verify_data member of a server's
Finished message.
type finishedMsg struct {
verifyData []byte
}
func (m *finishedMsg) marshal() ([]byte, error)
func (m *finishedMsg) unmarshal(data []byte) bool
type halfConn struct {
sync.Mutex
mac hash.Hash
}
A halfConn represents one direction of the record layer connection, either
sending or receiving.
func (hc *halfConn) changeCipherSpec() error
changeCipherSpec changes the encryption and MAC states to the ones
previously passed to prepareCipherSpec.
func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error)
decrypt authenticates and decrypts the record if protection is active at
this stage. The returned plaintext might overlap with the input.
func (hc *halfConn) encrypt(record, payload []byte, rand io.Reader) ([]byte, error)
encrypt encrypts payload, adding the appropriate nonce and/or MAC,
and appends it to record, which must already contain the record header.
func (hc *halfConn) explicitNonceLen() int
explicitNonceLen returns the number of bytes of explicit nonce or IV
included in each record. Explicit nonces are present only in CBC modes after
TLS 1.0 and in certain AEAD modes in TLS 1.2.
func (hc *halfConn) incSeq()
incSeq increments the sequence number.
func (hc *halfConn) prepareCipherSpec(version uint16, cipher any, mac hash.Hash)
prepareCipherSpec sets the encryption and MAC states that a subsequent
changeCipherSpec will use.
func (hc *halfConn) setErrorLocked(err error) error
func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, level QUICEncryptionLevel, secret []byte)
type handshakeMessage interface {
marshal() ([]byte, error)
unmarshal([]byte) bool
}
type handshakeMessageWithOriginalBytes interface {
handshakeMessage
originalBytes() []byte
}
type helloRequestMsg struct {
}
func (*helloRequestMsg) marshal() ([]byte, error)
func (*helloRequestMsg) unmarshal(data []byte) bool
type keyAgreement interface {
generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error)
processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error)
processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error
generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
}
A keyAgreement implements the client and server side of a TLS 1.0–1.2 key
agreement protocol by generating and processing key exchange messages.
func ecdheECDSAKA(version uint16) keyAgreement
func ecdheRSAKA(version uint16) keyAgreement
func rsaKA(version uint16) keyAgreement
type keyShare struct {
group CurveID
data []byte
}
TLS 1.3 Key Share. See RFC 8446, Section 4.2.8.
type keySharePrivateKeys struct {
curveID CurveID
ecdhe *ecdh.PrivateKey
mlkem *mlkem.DecapsulationKey768
}
type keyUpdateMsg struct {
updateRequested bool
}
func (m *keyUpdateMsg) marshal() ([]byte, error)
func (m *keyUpdateMsg) unmarshal(data []byte) bool
type listener struct {
net.Listener
config *Config
}
A listener implements a network listener (net.Listener) for TLS connections.
func (l *listener) Accept() (net.Conn, error)
Accept waits for and returns the next incoming TLS connection. The returned
connection is of type *Conn.
type lruSessionCache struct {
sync.Mutex
m map[string]*list.Element
q *list.List
capacity int
}
lruSessionCache is a ClientSessionCache implementation that uses an LRU
caching strategy.
func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool)
Get returns the ClientSessionState value associated with a given key.
It returns (nil, false) if no value is found.
func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState)
Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil,
the entry corresponding to sessionKey is removed from the cache instead.
type lruSessionCacheEntry struct {
sessionKey string
state *ClientSessionState
}
type marshalingFunction func(b *cryptobyte.Builder) error
The marshalingFunction type is an adapter to allow the use of ordinary
functions as cryptobyte.MarshalingValue.
func (f marshalingFunction) Marshal(b *cryptobyte.Builder) error
type newSessionTicketMsg struct {
ticket []byte
}
func (m *newSessionTicketMsg) marshal() ([]byte, error)
func (m *newSessionTicketMsg) unmarshal(data []byte) bool
type newSessionTicketMsgTLS13 struct {
lifetime uint32
ageAdd uint32
nonce []byte
label []byte
maxEarlyData uint32
}
func (m *newSessionTicketMsgTLS13) marshal() ([]byte, error)
func (m *newSessionTicketMsgTLS13) unmarshal(data []byte) bool
type permanentError struct {
err net.Error
}
func (e *permanentError) Error() string
func (e *permanentError) Temporary() bool
func (e *permanentError) Timeout() bool
func (e *permanentError) Unwrap() error
type prefixNonceAEAD struct {
nonce [aeadNonceLength]byte
aead cipher.AEAD
}
prefixNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to
each call.
func (f *prefixNonceAEAD) NonceSize() int
func (f *prefixNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error)
func (f *prefixNonceAEAD) Overhead() int
func (f *prefixNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte
func (f *prefixNonceAEAD) explicitNonceLen() int
type prfFunc func(secret []byte, label string, seed []byte, keyLen int) []byte
func prf12(hashFunc func() hash.Hash) prfFunc
prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246,
Section 5.
func prfAndHashForVersion(version uint16, suite *cipherSuite) (prfFunc, crypto.Hash)
func prfForVersion(version uint16, suite *cipherSuite) prfFunc
type pskIdentity struct {
label []byte
obfuscatedTicketAge uint32
}
TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved
session. See RFC 8446, Section 4.2.11.
type quicState struct {
events []QUICEvent
nextEvent int
eventArr [8]QUICEvent
started bool
cancel context.CancelFunc
waitingForDrain bool
readbuf []byte
enableSessionEvents bool
}
type rawExtension struct {
extType uint16
data []byte
}
func extractRawExtensions(hello *clientHelloMsg) ([]rawExtension, error)
type recordType uint8
TLS record types.
const (
recordTypeChangeCipherSpec recordType = 20
recordTypeAlert recordType = 21
recordTypeHandshake recordType = 22
recordTypeApplicationData recordType = 23
)
type rsaKeyAgreement struct{}
rsaKeyAgreement implements the standard TLS key agreement where the client
encrypts the pre-master secret to the server's public key.
func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error)
func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error)
func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error)
func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error
type serverHandshakeState struct {
c *Conn
ctx context.Context
clientHello *clientHelloMsg
hello *serverHelloMsg
suite *cipherSuite
ecdheOk bool
ecSignOk bool
rsaDecryptOk bool
rsaSignOk bool
sessionState *SessionState
finishedHash finishedHash
masterSecret []byte
cert *Certificate
}
serverHandshakeState contains details of a server handshake in progress.
It's discarded once the handshake has completed.
func (hs *serverHandshakeState) checkForResumption() error
checkForResumption reports whether we should perform resumption on this
connection.
func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool
func (hs *serverHandshakeState) doFullHandshake() error
func (hs *serverHandshakeState) doResumeHandshake() error
func (hs *serverHandshakeState) establishKeys() error
func (hs *serverHandshakeState) handshake() error
func (hs *serverHandshakeState) pickCipherSuite() error
func (hs *serverHandshakeState) processClientHello() error
func (hs *serverHandshakeState) readFinished(out []byte) error
func (hs *serverHandshakeState) sendFinished(out []byte) error
func (hs *serverHandshakeState) sendSessionTicket() error
type serverHandshakeStateTLS13 struct {
c *Conn
ctx context.Context
clientHello *clientHelloMsg
hello *serverHelloMsg
sentDummyCCS bool
usingPSK bool
earlyData bool
suite *cipherSuiteTLS13
cert *Certificate
sigAlg SignatureScheme
earlySecret *tls13.EarlySecret
sharedKey []byte
handshakeSecret *tls13.HandshakeSecret
masterSecret *tls13.MasterSecret
transcript hash.Hash
clientFinished []byte
echContext *echServerContext
}
func (hs *serverHandshakeStateTLS13) checkForResumption() error
func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) (*keyShare, error)
func (hs *serverHandshakeStateTLS13) handshake() error
func (hs *serverHandshakeStateTLS13) pickCertificate() error
func (hs *serverHandshakeStateTLS13) processClientHello() error
func (hs *serverHandshakeStateTLS13) readClientCertificate() error
func (hs *serverHandshakeStateTLS13) readClientFinished() error
func (hs *serverHandshakeStateTLS13) requestClientCert() bool
func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error
sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix
D.4.
func (hs *serverHandshakeStateTLS13) sendServerCertificate() error
func (hs *serverHandshakeStateTLS13) sendServerFinished() error
func (hs *serverHandshakeStateTLS13) sendServerParameters() error
func (hs *serverHandshakeStateTLS13) sendSessionTickets() error
func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool
type serverHelloDoneMsg struct{}
func (m *serverHelloDoneMsg) marshal() ([]byte, error)
func (m *serverHelloDoneMsg) unmarshal(data []byte) bool
type serverHelloMsg struct {
original []byte
vers uint16
random []byte
sessionId []byte
cipherSuite uint16
compressionMethod uint8
ocspStapling bool
ticketSupported bool
secureRenegotiationSupported bool
secureRenegotiation []byte
extendedMasterSecret bool
alpnProtocol string
scts [][]byte
supportedVersion uint16
serverShare keyShare
selectedIdentityPresent bool
selectedIdentity uint16
supportedPoints []uint8
encryptedClientHello []byte
serverNameAck bool
cookie []byte
selectedGroup CurveID
}
func (m *serverHelloMsg) marshal() ([]byte, error)
func (m *serverHelloMsg) originalBytes() []byte
func (m *serverHelloMsg) unmarshal(data []byte) bool
type serverKeyExchangeMsg struct {
key []byte
}
func (m *serverKeyExchangeMsg) marshal() ([]byte, error)
func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool
type ticketKey struct {
aesKey [16]byte
hmacKey [16]byte
created time.Time
}
ticketKey is the internal representation of a session ticket key.
type timeoutError struct{}
func (timeoutError) Error() string
func (timeoutError) Temporary() bool
func (timeoutError) Timeout() bool
type transcriptHash interface {
Write([]byte) (int, error)
}
type xorNonceAEAD struct {
nonceMask [aeadNonceLength]byte
aead cipher.AEAD
}
xorNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce before
each call.
func (f *xorNonceAEAD) NonceSize() int
func (f *xorNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error)
func (f *xorNonceAEAD) Overhead() int
func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte
func (f *xorNonceAEAD) explicitNonceLen() int
BUG: The crypto/tls package only implements some countermeasures
against Lucky13 attacks on CBC-mode encryption, and only on SHA1
crypto/tls/fipsonly
func init()
crypto/tls/internal/fips140tls
func Force()
Force forces crypto/tls to restrict TLS configurations to FIPS-approved
settings. By design, this call is impossible to undo (except in tests).
func Required() bool
Required reports whether FIPS-approved settings are required.
Required is true if FIPS 140-3 mode is enabled with GODEBUG=fips140=on, or
if the crypto/tls/fipsonly package is imported by a Go+BoringCrypto build.
func TestingOnlyAbandon()
func init()
crypto/x509
func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error)
CreateCertificate creates a new X.509 v3 certificate based on a template.
The following members of template are currently used:
- AuthorityKeyId
- BasicConstraintsValid
- CRLDistributionPoints
- DNSNames
- EmailAddresses
- ExcludedDNSDomains
- ExcludedEmailAddresses
- ExcludedIPRanges
- ExcludedURIDomains
- ExtKeyUsage
- ExtraExtensions
- IPAddresses
- IsCA
- IssuingCertificateURL
- KeyUsage
- MaxPathLen
- MaxPathLenZero
- NotAfter
- NotBefore
- OCSPServer
- PermittedDNSDomains
- PermittedDNSDomainsCritical
- PermittedEmailAddresses
- PermittedIPRanges
- PermittedURIDomains
- PolicyIdentifiers (see note below)
- Policies (see note below)
- SerialNumber
- SignatureAlgorithm
- Subject
- SubjectKeyId
- URIs
- UnknownExtKeyUsage
The certificate is signed by parent. If parent is equal to template then
the certificate is self-signed. The parameter pub is the public key of the
certificate to be generated and priv is the private key of the signer.
The returned slice is the certificate in DER encoding.
The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
ed25519.PublicKey. pub must be a supported key type, and priv must be a
crypto.Signer with a supported public key.
The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
unless the resulting certificate is self-signed. Otherwise the value from
template will be used.
If SubjectKeyId from template is empty and the template is a CA,
SubjectKeyId will be generated from the hash of the public key.
If template.SerialNumber is nil, a serial number will be generated which
conforms to RFC 5280, Section 4.1.2.2 using entropy from rand.
The PolicyIdentifier and Policies fields can both be used to marshal
certificate policy OIDs. By default, only the Policies is marshaled,
but if the GODEBUG setting "x509usepolicies" has the value "0", the
PolicyIdentifiers field will be marshaled instead of the Policies field.
This changed in Go 1.24. The Policies field can be used to marshal policy
OIDs which have components that are larger than 31 bits.
func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error)
CreateCertificateRequest creates a new certificate request based on a
template. The following members of template are used:
- SignatureAlgorithm
- Subject
- DNSNames
- EmailAddresses
- IPAddresses
- URIs
- ExtraExtensions
- Attributes (deprecated)
priv is the private key to sign the CSR with, and the corresponding public
key will be included in the CSR. It must implement crypto.Signer and
its Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey
or a ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
ed25519.PrivateKey satisfies this.)
The returned slice is the certificate request in DER encoding.
func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error)
CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
according to RFC 5280, based on template.
The CRL is signed by priv which should be the private key associated with
the public key in the issuer certificate.
The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
order to use it as a CRL issuer.
The issuer distinguished name CRL field and authority key identifier
extension are populated using the issuer certificate. issuer must have
SubjectKeyId set.
func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)
DecryptPEMBlock takes a PEM block encrypted according to RFC 1423 and the
password used to encrypt it and returns a slice of decrypted DER encoded
bytes. It inspects the DEK-Info header to determine the algorithm used
for decryption. If no DEK-Info header is present, an error is returned.
If an incorrect password is detected an IncorrectPasswordError is returned.
Because of deficiencies in the format, it's not always possible to detect
an incorrect password. In these cases no error will be returned but the
decrypted DER bytes will be random noise.
Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by
design. Since it does not authenticate the ciphertext, it is vulnerable to
padding oracle attacks that can let an attacker recover the plaintext.
func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)
EncryptPEMBlock returns a PEM block of the specified type holding the
given DER encoded data encrypted with the specified algorithm and password
according to RFC 1423.
Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by
design. Since it does not authenticate the ciphertext, it is vulnerable to
padding oracle attacks that can let an attacker recover the plaintext.
func IsEncryptedPEMBlock(b *pem.Block) bool
IsEncryptedPEMBlock returns whether the PEM block is password encrypted
according to RFC 1423.
Deprecated: Legacy PEM encryption as specified in RFC 1423 is insecure by
design. Since it does not authenticate the ciphertext, it is vulnerable to
padding oracle attacks that can let an attacker recover the plaintext.
func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
MarshalECPrivateKey converts an EC private key to SEC 1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE
KEY". For a more flexible key format which is not EC specific, use
MarshalPKCS8PrivateKey.
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
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". For a more flexible key format which is not RSA specific, use
MarshalPKCS8PrivateKey.
The key must have passed validation by calling rsa.PrivateKey.Validate
first. MarshalPKCS1PrivateKey calls rsa.PrivateKey.Precompute, which may
modify the key if not already precomputed.
func MarshalPKCS1PublicKey(key *rsa.PublicKey) []byte
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".
func MarshalPKCS8PrivateKey(key any) ([]byte, error)
MarshalPKCS8PrivateKey converts a private key to PKCS #8, ASN.1 DER form.
The following key types are currently supported: *rsa.PrivateKey,
*ecdsa.PrivateKey, ed25519.PrivateKey (not a pointer), and *ecdh.PrivateKey.
Unsupported key types result in an error.
This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".
MarshalPKCS8PrivateKey runs rsa.PrivateKey.Precompute on RSA keys.
func MarshalPKIXPublicKey(pub any) ([]byte, error)
MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
The encoded public key is a SubjectPublicKeyInfo structure (see RFC 5280,
Section 4.1).
The following key types are currently supported: *rsa.PublicKey,
*ecdsa.PublicKey, ed25519.PublicKey (not a pointer), and *ecdh.PublicKey.
Unsupported key types result in an error.
This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error)
ParseCRL parses a CRL from the given bytes. It's often the case that PEM
encoded CRLs will appear where they should be DER encoded, so this function
will transparently handle PEM encoding as long as there isn't any leading
garbage.
Deprecated: Use ParseRevocationList instead.
func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error)
ParseDERCRL parses a DER encoded CRL from the given bytes.
Deprecated: Use ParseRevocationList instead.
func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error)
ParseECPrivateKey parses an EC private key in SEC 1, ASN.1 DER form.
This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY".
func ParsePKCS1PrivateKey(der []byte) (*rsa.PrivateKey, error)
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".
Before Go 1.24, the CRT parameters were ignored and recomputed. To restore
the old behavior, use the GODEBUG=x509rsacrt=0 environment variable.
func ParsePKCS1PublicKey(der []byte) (*rsa.PublicKey, error)
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".
func ParsePKCS8PrivateKey(der []byte) (key any, err error)
ParsePKCS8PrivateKey parses an unencrypted private key in PKCS #8, ASN.1 DER
form.
It returns a *rsa.PrivateKey, an *ecdsa.PrivateKey, an ed25519.PrivateKey
(not a pointer), or an *ecdh.PrivateKey (for X25519). More types might be
supported in the future.
This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".
Before Go 1.24, the CRT parameters of RSA keys were ignored and recomputed.
To restore the old behavior, use the GODEBUG=x509rsacrt=0 environment
variable.
func ParsePKIXPublicKey(derBytes []byte) (pub any, err error)
ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded
public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).
It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
ed25519.PublicKey (not a pointer), or *ecdh.PublicKey (for X25519). More
types might be supported in the future.
This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
func SetFallbackRoots(roots *CertPool)
SetFallbackRoots sets the roots to use during certificate verification,
if no custom roots are specified and a platform verifier or a system
certificate pool is not available (for instance in a container which does
not have a root certificate bundle). SetFallbackRoots will panic if roots is
nil.
SetFallbackRoots may only be called once, if called multiple times it will
panic.
The fallback behavior can be forced on all platforms, even when there
is a system certificate pool, by setting GODEBUG=x509usefallbackroots=1
(note that on Windows and macOS this will disable usage of the platform
verification APIs and cause the pure Go verifier to be used). Setting
x509usefallbackroots=1 without calling SetFallbackRoots has no effect.
func alreadyInChain(candidate *Certificate, chain []*Certificate) bool
alreadyInChain checks whether a candidate certificate is present in a chain.
Rather than doing a direct byte for byte equivalency check, we check if the
subject, public key, and SAN, if present, are equal. This prevents loops
that are created by mutual cross-signatures, or other cross-signature bridge
oddities.
func appendBase128BigInt(dst []byte, n *big.Int) []byte
func appendBase128Int(dst []byte, n uint64) []byte
func asn1BitLength(bitString []byte) int
asn1BitLength returns the bit-length of bitString by considering the
most-significant bit in a byte to be the "first" bit. This convention
matches ASN.1, but differs from almost everything else.
func base128BigIntLength(n *big.Int) int
func base128IntLength(n uint64) int
func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error)
func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error)
func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool
func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error)
checkSignature verifies that signature is a valid signature over signed from
a crypto.PublicKey.
func domainToReverseLabels(domain string) (reverseLabels []string, ok bool)
domainToReverseLabels converts a textual domain name like foo.example.com to
the list of labels in reverse order, e.g. ["com", "example", "foo"].
func forEachSAN(der cryptobyte.String, callback func(tag int, data []byte) error) error
func init()
func initSystemRoots()
func isIA5String(s string) error
func isPrintable(b byte) bool
isPrintable reports whether the given b is in the ASN.1 PrintableString set.
This is a simplified version of encoding/asn1.isPrintable.
func isSameDirSymlink(f fs.DirEntry, dir string) bool
isSameDirSymlink reports whether fi in dir is a symlink with a target not
containing a slash.
func isValidIPMask(mask []byte) bool
isValidIPMask reports whether mask consists of zero or more 1 bits, followed
by zero bits.
func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error)
func marshalCertificatePolicies(policies []OID, policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error)
func marshalECDHPrivateKey(key *ecdh.PrivateKey) ([]byte, error)
marshalECDHPrivateKey marshals an EC private key into ASN.1, DER format
suitable for NIST curves.
func marshalECPrivateKeyWithOID(key *ecdsa.PrivateKey, oid asn1.ObjectIdentifier) ([]byte, error)
marshalECPrivateKeyWithOID marshals an EC private key into ASN.1, DER format
and sets the curve ID to the given OID, or omits it if OID is nil.
func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error)
func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error)
func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error)
func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error)
marshalSANs marshals a list of addresses into a the contents of an X.509
SubjectAlternativeName extension.
func matchDomainConstraint(domain, constraint string) (bool, error)
func matchEmailConstraint(mailbox rfc2821Mailbox, constraint string) (bool, error)
func matchExactly(hostA, hostB string) bool
func matchHostnames(pattern, host string) bool
func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error)
func matchURIConstraint(uri *url.URL, constraint string) (bool, error)
func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve
func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error)
newRawAttributes converts AttributeTypeAndValueSETs from a template
CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
func oidFromECDHCurve(curve ecdh.Curve) (asn1.ObjectIdentifier, bool)
func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool)
func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool)
func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool
oidInExtensions reports whether an extension with the given oid exists in
extensions.
func parseAI(der cryptobyte.String) (pkix.AlgorithmIdentifier, error)
func parseASN1String(tag cryptobyte_asn1.Tag, value []byte) (string, error)
parseASN1String parses the ASN.1 string types T61String, PrintableString,
UTF8String, BMPString, IA5String, and NumericString. This is mostly copied
from the respective encoding/asn1.parse... methods, rather than just
increasing the API surface of that package.
func parseAuthorityKeyIdentifier(e pkix.Extension) ([]byte, error)
func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, failed bool)
func parseBasicConstraintsExtension(der cryptobyte.String) (bool, int, error)
func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error)
parseCSRExtensions parses the attributes from a CSR and extracts any
requested extensions.
func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error)
parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
The OID for the named curve may be provided from another source (such as the
PKCS8 container) - if it is provided then use this instead of the OID that
may exist in the EC private key structure.
func parseExtension(der cryptobyte.String) (pkix.Extension, error)
func parseName(raw cryptobyte.String) (*pkix.RDNSequence, error)
parseName parses a DER encoded Name as defined in RFC 5280. We may want to
export this function in the future for use in crypto/tls.
func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error)
func parsePublicKey(keyData *publicKeyInfo) (any, error)
func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET
parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
func parseSANExtension(der cryptobyte.String) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error)
func parseTime(der *cryptobyte.String) (time.Time, error)
func parseValidity(der cryptobyte.String) (time.Time, time.Time, error)
func policiesValid(chain []*Certificate, opts VerifyOptions) bool
func processExtensions(out *Certificate) error
func readUniqueDirectoryEntries(dir string) ([]fs.DirEntry, error)
readUniqueDirectoryEntries is like os.ReadDir but omits symlinks that point
within the directory.
func reverseBitsInAByte(in byte) byte
func signTBS(tbs []byte, key crypto.Signer, sigAlg SignatureAlgorithm, rand io.Reader) ([]byte, error)
func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error
func subjectBytes(cert *Certificate) ([]byte, error)
func toLowerCaseASCII(in string) string
toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1.
We use an explicitly ASCII function to avoid any sharp corners resulting
from performing Unicode operations on DNS labels.
func validHostname(host string, isPattern bool) bool
validHostname reports whether host is a valid hostname that can be matched
or matched against according to RFC 6125 2.2, with some leniency to
accommodate legacy values.
func validHostnameInput(host string) bool
func validHostnamePattern(host string) bool
TYPES
type CertPool struct {
lazyCerts []lazyCert
haveSum map[sum224]bool
systemPool bool
}
CertPool is a set of certificates.
func NewCertPool() *CertPool
NewCertPool returns a new, empty CertPool.
func SystemCertPool() (*CertPool, error)
SystemCertPool returns a copy of the system cert pool.
On Unix systems other than macOS the environment variables SSL_CERT_FILE
and SSL_CERT_DIR can be used to override the system default locations for
the SSL certificate file and SSL certificate files directory, respectively.
The latter can be a colon-separated list.
Any mutations to the returned pool are not written to disk and do not affect
any other pool returned by SystemCertPool.
New changes in the system cert pool might not be reflected in subsequent
calls.
func loadSystemRoots() (*CertPool, error)
func systemRootsPool() *CertPool
func (s *CertPool) AddCert(cert *Certificate)
AddCert adds a certificate to a pool.
func (s *CertPool) AddCertWithConstraint(cert *Certificate, constraint func([]*Certificate) error)
AddCertWithConstraint adds a certificate to the pool with the additional
constraint. When Certificate.Verify builds a chain which is rooted by cert,
it will additionally pass the whole chain to constraint to determine
its validity. If constraint returns a non-nil error, the chain will be
discarded. constraint may be called concurrently from multiple goroutines.
func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)
AppendCertsFromPEM attempts to parse a series of PEM encoded certificates.
It appends any certificates found to s and reports whether any certificates
were successfully parsed.
On many Linux systems, /etc/ssl/cert.pem will contain the system wide set of
root CAs in a format suitable for this function.
func (s *CertPool) Clone() *CertPool
Clone returns a copy of s.
func (s *CertPool) Equal(other *CertPool) bool
Equal reports whether s and other are equal.
func (s *CertPool) Subjects() [][]byte
Subjects returns a list of the DER-encoded subjects of all of the
certificates in the pool.
Deprecated: if s was returned by SystemCertPool, Subjects will not include
the system roots.
func (s *CertPool) addCertFunc(rawSum224 sum224, rawSubject string, getCert func() (*Certificate, error), constraint func([]*Certificate) error)
addCertFunc adds metadata about a certificate to a pool, along with a func
to fetch that certificate later when needed.
The rawSubject is Certificate.RawSubject and must be non-empty. The getCert
func may be called 0 or more times.
func (s *CertPool) cert(n int) (*Certificate, func([]*Certificate) error, error)
cert returns cert index n in s.
func (s *CertPool) contains(cert *Certificate) bool
func (s *CertPool) findPotentialParents(cert *Certificate) []potentialParent
findPotentialParents returns the certificates in s which might have signed
cert.
func (s *CertPool) len() int
len returns the number of certs in the set. A nil set is a valid empty set.
type Certificate struct {
Signature []byte
SignatureAlgorithm SignatureAlgorithm
PublicKeyAlgorithm PublicKeyAlgorithm
PublicKey any
Version int
SerialNumber *big.Int
Issuer pkix.Name
Subject pkix.Name
KeyUsage KeyUsage
Extensions []pkix.Extension
ExtraExtensions []pkix.Extension
UnhandledCriticalExtensions []asn1.ObjectIdentifier
BasicConstraintsValid bool
IsCA bool
MaxPathLen int
MaxPathLenZero bool
SubjectKeyId []byte
AuthorityKeyId []byte
OCSPServer []string
IssuingCertificateURL []string
DNSNames []string
EmailAddresses []string
IPAddresses []net.IP
URIs []*url.URL
PermittedDNSDomains []string
ExcludedDNSDomains []string
PermittedIPRanges []*net.IPNet
ExcludedIPRanges []*net.IPNet
PermittedEmailAddresses []string
ExcludedEmailAddresses []string
PermittedURIDomains []string
ExcludedURIDomains []string
CRLDistributionPoints []string
PolicyIdentifiers []asn1.ObjectIdentifier
Policies []OID
InhibitAnyPolicy int
InhibitAnyPolicyZero bool
InhibitPolicyMapping int
InhibitPolicyMappingZero bool
RequireExplicitPolicy int
RequireExplicitPolicyZero bool
PolicyMappings []PolicyMapping
}
A Certificate represents an X.509 certificate.
func ParseCertificate(der []byte) (*Certificate, error)
ParseCertificate parses a single certificate from the given ASN.1 DER data.
Before Go 1.23, ParseCertificate accepted certificates with negative serial
numbers. This behavior can be restored by including "x509negativeserial=1"
in the GODEBUG environment variable.
func ParseCertificates(der []byte) ([]*Certificate, error)
ParseCertificates parses one or more certificates from the given ASN.1 DER
data. The certificates must be concatenated with no intermediate padding.
func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate
func parseCertificate(der []byte) (*Certificate, error)
func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error
CheckCRLSignature checks that the signature in crl is from c.
Deprecated: Use RevocationList.CheckSignatureFrom instead.
func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error
CheckSignature verifies that signature is a valid signature over signed from
c's public key.
This is a low-level API that performs no validity checks on the certificate.
MD5WithRSA signatures are rejected, while SHA1WithRSA and ECDSAWithSHA1
signatures are currently accepted.
func (c *Certificate) CheckSignatureFrom(parent *Certificate) error
CheckSignatureFrom verifies that the signature on c is a valid signature
from parent.
This is a low-level API that performs very limited checks, and not a full
path verifier. Most users should use Certificate.Verify instead.
func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)
CreateCRL returns a DER encoded CRL, signed by this Certificate, that
contains the given list of revoked certificates.
Deprecated: this method does not generate an RFC 5280 conformant X.509
v2 CRL. To generate a standards compliant CRL, use CreateRevocationList
instead.
func (c *Certificate) Equal(other *Certificate) bool
func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
Verify attempts to verify c by building one or more chains from c to a
certificate in opts.Roots, using certificates in opts.Intermediates if
needed. If successful, it returns one or more chains where the first element
of the chain is c and the last element is from opts.Roots.
If opts.Roots is nil, the platform verifier might be used, and verification
details might differ from what is described below. If system roots are
unavailable the returned error will be of type SystemRootsError.
Name constraints in the intermediates will be applied to all names claimed
in the chain, not just opts.DNSName. Thus it is invalid for a leaf to claim
example.com if an intermediate doesn't permit it, even if example.com is
not the name being validated. Note that DirectoryName constraints are not
supported.
Name constraint validation follows the rules from RFC 5280, with the
addition that DNS name constraints may use the leading period format defined
for emails and URIs. When a constraint has a leading period it indicates
that at least one additional label must be prepended to the constrained name
to be considered valid.
Extended Key Usage values are enforced nested down a chain, so an
intermediate or root that enumerates EKUs prevents a leaf from asserting an
EKU not in that list. (While this is not specified, it is common practice in
order to limit the types of certificates a CA can issue.)
Certificates that use SHA1WithRSA and ECDSAWithSHA1 signatures are not
supported, and will not be used to build chains.
Certificates other than c in the returned chains should not be modified.
WARNING: this function doesn't do any revocation checking.
func (c *Certificate) VerifyHostname(h string) error
VerifyHostname returns nil if c is a valid certificate for the named host.
Otherwise it returns an error describing the mismatch.
IP addresses can be optionally enclosed in square brackets and are checked
against the IPAddresses field. Other names are checked case insensitively
against the DNSNames field. If the names are valid hostnames, the
certificate fields can have a wildcard as the complete left-most label (e.g.
*.example.com).
Note that the legacy Common Name field is ignored.
func (c *Certificate) buildChains(currentChain []*Certificate, sigChecks *int, opts *VerifyOptions) (chains [][]*Certificate, err error)
func (c *Certificate) checkNameConstraints(count *int,
maxConstraintComparisons int,
nameType string,
name string,
parsedName any,
match func(parsedName, constraint any) (match bool, err error),
permitted, excluded any) error
checkNameConstraints checks that c permits a child certificate to claim the
given name, of type nameType. The argument parsedName contains the parsed
form of name, suitable for passing to the match function. The total number
of comparisons is tracked in the given count and should not exceed the given
limit.
func (c *Certificate) getSANExtension() []byte
func (c *Certificate) hasNameConstraints() bool
func (c *Certificate) hasSANExtension() bool
func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error
isValid performs validity checks on c given that it is a candidate to append
to the chain in currentChain.
func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error)
type CertificateInvalidError struct {
Cert *Certificate
Reason InvalidReason
Detail string
}
CertificateInvalidError results when an odd error occurs. Users of this
library probably want to handle all these errors uniformly.
func (e CertificateInvalidError) Error() string
type CertificateRequest struct {
Version int
Signature []byte
SignatureAlgorithm SignatureAlgorithm
PublicKeyAlgorithm PublicKeyAlgorithm
PublicKey any
Subject pkix.Name
Attributes []pkix.AttributeTypeAndValueSET
Extensions []pkix.Extension
ExtraExtensions []pkix.Extension
DNSNames []string
EmailAddresses []string
IPAddresses []net.IP
URIs []*url.URL
}
CertificateRequest represents a PKCS #10, certificate signature request.
func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
ParseCertificateRequest parses a single certificate request from the given
ASN.1 DER data.
func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error)
func (c *CertificateRequest) CheckSignature() error
CheckSignature reports whether the signature on c is valid.
type ConstraintViolationError struct{}
ConstraintViolationError results when a requested usage is not permitted by
a certificate. For example: checking a signature when the public key isn't a
certificate signing key.
func (ConstraintViolationError) Error() string
type ExtKeyUsage int
ExtKeyUsage represents an extended set of actions that are valid for a given
key. Each of the ExtKeyUsage* constants define a unique action.
const (
ExtKeyUsageAny ExtKeyUsage = iota
ExtKeyUsageServerAuth
ExtKeyUsageClientAuth
ExtKeyUsageCodeSigning
ExtKeyUsageEmailProtection
ExtKeyUsageIPSECEndSystem
ExtKeyUsageIPSECTunnel
ExtKeyUsageIPSECUser
ExtKeyUsageTimeStamping
ExtKeyUsageOCSPSigning
ExtKeyUsageMicrosoftServerGatedCrypto
ExtKeyUsageNetscapeServerGatedCrypto
ExtKeyUsageMicrosoftCommercialCodeSigning
ExtKeyUsageMicrosoftKernelCodeSigning
)
func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool)
func parseExtKeyUsageExtension(der cryptobyte.String) ([]ExtKeyUsage, []asn1.ObjectIdentifier, error)
type HostnameError struct {
Certificate *Certificate
Host string
}
HostnameError results when the set of authorized names doesn't match the
requested name.
func (h HostnameError) Error() string
type InsecureAlgorithmError SignatureAlgorithm
An InsecureAlgorithmError indicates that the SignatureAlgorithm used to
generate the signature is not secure, and the signature has been rejected.
func (e InsecureAlgorithmError) Error() string
type InvalidReason int
const (
NotAuthorizedToSign InvalidReason = iota
Expired
CANotAuthorizedForThisName
TooManyIntermediates
IncompatibleUsage
NameMismatch
NameConstraintsWithoutSANs
UnconstrainedName
TooManyConstraints
CANotAuthorizedForExtKeyUsage
NoValidChains
)
type KeyUsage int
KeyUsage represents the set of actions that are valid for a given key.
It's a bitmap of the KeyUsage* constants.
const (
KeyUsageDigitalSignature KeyUsage = 1 << iota
KeyUsageContentCommitment
KeyUsageKeyEncipherment
KeyUsageDataEncipherment
KeyUsageKeyAgreement
KeyUsageCertSign
KeyUsageCRLSign
KeyUsageEncipherOnly
KeyUsageDecipherOnly
)
func parseKeyUsageExtension(der cryptobyte.String) (KeyUsage, error)
type OID struct {
der []byte
}
An OID represents an ASN.1 OBJECT IDENTIFIER.
func OIDFromInts(oid []uint64) (OID, error)
OIDFromInts creates a new OID using ints, each integer is a separate
component.
func ParseOID(oid string) (OID, error)
ParseOID parses a Object Identifier string, represented by ASCII numbers
separated by dots.
func mustNewOIDFromInts(ints []uint64) OID
func newOIDFromDER(der []byte) (OID, bool)
func parseCertificatePoliciesExtension(der cryptobyte.String) ([]OID, error)
func (o OID) AppendBinary(b []byte) ([]byte, error)
AppendBinary implements encoding.BinaryAppender
func (o OID) AppendText(b []byte) ([]byte, error)
AppendText implements encoding.TextAppender
func (oid OID) Equal(other OID) bool
Equal returns true when oid and other represents the same Object Identifier.
func (oid OID) EqualASN1OID(other asn1.ObjectIdentifier) bool
EqualASN1OID returns whether an OID equals an asn1.ObjectIdentifier.
If asn1.ObjectIdentifier cannot represent the OID specified by oid, because
a component of OID requires more than 31 bits, it returns false.
func (o OID) MarshalBinary() ([]byte, error)
MarshalBinary implements encoding.BinaryMarshaler
func (o OID) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler
func (oid OID) String() string
Strings returns the string representation of the Object Identifier.
func (o *OID) UnmarshalBinary(b []byte) error
UnmarshalBinary implements encoding.BinaryUnmarshaler
func (o *OID) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler
func (oid OID) toASN1OID() (asn1.ObjectIdentifier, bool)
func (o *OID) unmarshalOIDText(oid string) error
type PEMCipher int
const (
_ PEMCipher = iota
PEMCipherDES
PEMCipher3DES
PEMCipherAES128
PEMCipherAES192
PEMCipherAES256
)
Possible values for the EncryptPEMBlock encryption algorithm.
type PolicyMapping struct {
IssuerDomainPolicy OID
SubjectDomainPolicy OID
}
PolicyMapping represents a policy mapping entry in the policyMappings
extension.
type PublicKeyAlgorithm int
const (
UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
RSA
ECDSA
Ed25519
)
func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm
getPublicKeyAlgorithmFromOID returns the exposed PublicKeyAlgorithm
identifier for public key types supported in certificates and CSRs. Marshal
and Parse functions may support a different set of public key types.
func (algo PublicKeyAlgorithm) String() string
type RevocationList struct {
Raw []byte
RawTBSRevocationList []byte
RawIssuer []byte
Issuer pkix.Name
AuthorityKeyId []byte
Signature []byte
SignatureAlgorithm SignatureAlgorithm
RevokedCertificateEntries []RevocationListEntry
RevokedCertificates []pkix.RevokedCertificate
Number *big.Int
ThisUpdate time.Time
NextUpdate time.Time
Extensions []pkix.Extension
ExtraExtensions []pkix.Extension
}
RevocationList represents a Certificate Revocation List (CRL) as specified
by RFC 5280.
func ParseRevocationList(der []byte) (*RevocationList, error)
ParseRevocationList parses a X509 v2 Certificate Revocation List from the
given ASN.1 DER data.
func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error
CheckSignatureFrom verifies that the signature on rl is a valid signature
from issuer.
type RevocationListEntry struct {
Raw []byte
SerialNumber *big.Int
RevocationTime time.Time
ReasonCode int
Extensions []pkix.Extension
ExtraExtensions []pkix.Extension
}
RevocationListEntry represents an entry in the revokedCertificates sequence
of a CRL.
type SignatureAlgorithm int
const (
UnknownSignatureAlgorithm SignatureAlgorithm = iota
SHA256WithRSA
SHA384WithRSA
SHA512WithRSA
ECDSAWithSHA256
ECDSAWithSHA384
ECDSAWithSHA512
SHA256WithRSAPSS
SHA384WithRSAPSS
SHA512WithRSAPSS
PureEd25519
)
func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm
func signingParamsForKey(key crypto.Signer, sigAlgo SignatureAlgorithm) (SignatureAlgorithm, pkix.AlgorithmIdentifier, error)
signingParamsForKey returns the signature algorithm and its Algorithm
Identifier to use for signing, based on the key type. If sigAlgo is not zero
then it overrides the default.
func (algo SignatureAlgorithm) String() string
func (algo SignatureAlgorithm) hashFunc() crypto.Hash
func (algo SignatureAlgorithm) isRSAPSS() bool
type SystemRootsError struct {
Err error
}
SystemRootsError results when we fail to load the system root certificates.
func (se SystemRootsError) Error() string
func (se SystemRootsError) Unwrap() error
type UnhandledCriticalExtension struct{}
func (h UnhandledCriticalExtension) Error() string
type UnknownAuthorityError struct {
Cert *Certificate
hintErr error
hintCert *Certificate
}
UnknownAuthorityError results when the certificate issuer is unknown
func (e UnknownAuthorityError) Error() string
type VerifyOptions struct {
DNSName string
Intermediates *CertPool
Roots *CertPool
CurrentTime time.Time
KeyUsages []ExtKeyUsage
MaxConstraintComparisions int
CertificatePolicies []OID
inhibitPolicyMapping bool
requireExplicitPolicy bool
inhibitAnyPolicy bool
}
VerifyOptions contains parameters for Certificate.Verify.
type authKeyId struct {
Id []byte `asn1:"optional,tag:0"`
}
RFC 5280, 4.2.1.1
type authorityInfoAccess struct {
Method asn1.ObjectIdentifier
Location asn1.RawValue
}
RFC 5280, 4.2.2.1
type basicConstraints struct {
IsCA bool `asn1:"optional"`
MaxPathLen int `asn1:"optional,default:-1"`
}
type certificate struct {
TBSCertificate tbsCertificate
SignatureAlgorithm pkix.AlgorithmIdentifier
SignatureValue asn1.BitString
}
type certificateList struct {
TBSCertList tbsCertificateList
SignatureAlgorithm pkix.AlgorithmIdentifier
SignatureValue asn1.BitString
}
These structures reflect the ASN.1 structure of X.509 CRLs better than the
existing crypto/x509/pkix variants do. These mirror the existing certificate
structs in this file.
Notably, we include issuer as an asn1.RawValue, mirroring the behavior of
tbsCertificate and allowing raw (unparsed) subjects to be passed cleanly.
type certificateRequest struct {
Raw asn1.RawContent
TBSCSR tbsCertificateRequest
SignatureAlgorithm pkix.AlgorithmIdentifier
SignatureValue asn1.BitString
}
type distributionPoint struct {
DistributionPoint distributionPointName `asn1:"optional,tag:0"`
Reason asn1.BitString `asn1:"optional,tag:1"`
CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
}
RFC 5280, 4.2.1.14
type distributionPointName struct {
FullName []asn1.RawValue `asn1:"optional,tag:0"`
RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
}
type dsaAlgorithmParameters struct {
P, Q, G *big.Int
}
type ecPrivateKey struct {
Version int
PrivateKey []byte
NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"`
PublicKey asn1.BitString `asn1:"optional,explicit,tag:1"`
}
ecPrivateKey reflects an ASN.1 Elliptic Curve Private Key Structure.
References:
RFC 5915
Per RFC 5915 the NamedCurveOID is marked as ASN.1 OPTIONAL, however in most
cases it is not.
type lazyCert struct {
rawSubject []byte
constraint func([]*Certificate) error
getCert func() (*Certificate, error)
}
lazyCert is minimal metadata about a Cert and a func to retrieve it in its
normal expanded *Certificate form.
type pkcs1AdditionalRSAPrime struct {
Prime *big.Int
Exp *big.Int
Coeff *big.Int
}
type pkcs1PrivateKey struct {
Version int
N *big.Int
E int
D *big.Int
P *big.Int
Q *big.Int
Dp *big.Int `asn1:"optional"`
Dq *big.Int `asn1:"optional"`
Qinv *big.Int `asn1:"optional"`
AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"`
}
pkcs1PrivateKey is a structure which mirrors the PKCS #1 ASN.1 for an RSA
private key.
type pkcs1PublicKey struct {
N *big.Int
E int
}
pkcs1PublicKey reflects the ASN.1 structure of a PKCS #1 public key.
type pkcs8 struct {
Version int
Algo pkix.AlgorithmIdentifier
PrivateKey []byte
}
pkcs8 reflects an ASN.1, PKCS #8 PrivateKey. See
type pkixPublicKey struct {
Algo pkix.AlgorithmIdentifier
BitString asn1.BitString
}
pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
in RFC 3280.
type policyGraph struct {
strata []map[string]*policyGraphNode
parentIndex map[string][]*policyGraphNode
depth int
}
func newPolicyGraph() *policyGraph
func (pg *policyGraph) deleteLeaf(policy OID)
func (pg *policyGraph) incrDepth()
func (pg *policyGraph) insert(n *policyGraphNode)
func (pg *policyGraph) leafWithPolicy(policy OID) *policyGraphNode
func (pg *policyGraph) leaves() map[string]*policyGraphNode
func (pg *policyGraph) parentWithAnyPolicy() *policyGraphNode
func (pg *policyGraph) parents() iter.Seq[*policyGraphNode]
func (pg *policyGraph) parentsWithExpected(expected OID) []*policyGraphNode
func (pg *policyGraph) prune()
func (pg *policyGraph) validPolicyNodes() []*policyGraphNode
type policyGraphNode struct {
validPolicy OID
expectedPolicySet []OID
parents map[*policyGraphNode]bool
children map[*policyGraphNode]bool
}
func newPolicyGraphNode(valid OID, parents []*policyGraphNode) *policyGraphNode
type policyInformation struct {
Policy asn1.ObjectIdentifier
}
RFC 5280 4.2.1.4
type potentialParent struct {
cert *Certificate
constraint func([]*Certificate) error
}
type pssParameters struct {
Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
SaltLength int `asn1:"explicit,tag:2"`
TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
}
pssParameters reflects the parameters in an AlgorithmIdentifier that
specifies RSA PSS. See RFC 3447, Appendix A.2.3.
type publicKeyInfo struct {
Raw asn1.RawContent
Algorithm pkix.AlgorithmIdentifier
PublicKey asn1.BitString
}
type rfc1423Algo struct {
cipher PEMCipher
name string
cipherFunc func(key []byte) (cipher.Block, error)
keySize int
blockSize int
}
rfc1423Algo holds a method for enciphering a PEM block.
func cipherByKey(key PEMCipher) *rfc1423Algo
func cipherByName(name string) *rfc1423Algo
func (c rfc1423Algo) deriveKey(password, salt []byte) []byte
deriveKey uses a key derivation function to stretch the password into a key
with the number of bits our cipher requires. This algorithm was derived from
the OpenSSL source.
type rfc2821Mailbox struct {
local, domain string
}
rfc2821Mailbox represents a “mailbox” (which is an email address to most
people) by breaking it into the “local” (i.e. before the '@') and “domain”
parts.
func parseRFC2821Mailbox(in string) (mailbox rfc2821Mailbox, ok bool)
parseRFC2821Mailbox parses an email address into local and domain parts,
based on the ABNF for a “Mailbox” from RFC 2821. According to RFC 5280,
Section 4.2.1.6 that's correct for an rfc822Name from a certificate:
“The format of an rfc822Name is a "Mailbox" as defined in RFC 2821, Section
4.1.2”.
type sum224 [sha256.Size224]byte
type tbsCertificate struct {
Raw asn1.RawContent
Version int `asn1:"optional,explicit,default:0,tag:0"`
SerialNumber *big.Int
SignatureAlgorithm pkix.AlgorithmIdentifier
Issuer asn1.RawValue
Validity validity
Subject asn1.RawValue
PublicKey publicKeyInfo
UniqueId asn1.BitString `asn1:"optional,tag:1"`
SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
Extensions []pkix.Extension `asn1:"omitempty,optional,explicit,tag:3"`
}
type tbsCertificateList struct {
Raw asn1.RawContent
Version int `asn1:"optional,default:0"`
Signature pkix.AlgorithmIdentifier
Issuer asn1.RawValue
ThisUpdate time.Time
NextUpdate time.Time `asn1:"optional"`
RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"`
Extensions []pkix.Extension `asn1:"tag:0,optional,explicit"`
}
type tbsCertificateRequest struct {
Raw asn1.RawContent
Version int
Subject asn1.RawValue
PublicKey publicKeyInfo
RawAttributes []asn1.RawValue `asn1:"tag:0"`
}
type validity struct {
NotBefore, NotAfter time.Time
}
crypto/x509/pkix
func oidInAttributeTypeAndValue(oid asn1.ObjectIdentifier, atv []AttributeTypeAndValue) bool
oidInAttributeTypeAndValue reports whether a type with the given OID exists
in atv.
TYPES
type AlgorithmIdentifier struct {
Algorithm asn1.ObjectIdentifier
Parameters asn1.RawValue `asn1:"optional"`
}
AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC
5280, section 4.1.1.2.
type AttributeTypeAndValue struct {
Type asn1.ObjectIdentifier
Value any
}
AttributeTypeAndValue mirrors the ASN.1 structure of the same name in RFC
5280, Section 4.1.2.4.
type AttributeTypeAndValueSET struct {
Type asn1.ObjectIdentifier
Value [][]AttributeTypeAndValue `asn1:"set"`
}
AttributeTypeAndValueSET represents a set of ASN.1 sequences of
AttributeTypeAndValue sequences from RFC 2986 (PKCS #10).
type CertificateList struct {
TBSCertList TBSCertificateList
SignatureAlgorithm AlgorithmIdentifier
SignatureValue asn1.BitString
}
CertificateList represents the ASN.1 structure of the same name.
See RFC 5280, section 5.1. Use Certificate.CheckCRLSignature to verify the
signature.
Deprecated: x509.RevocationList should be used instead.
func (certList *CertificateList) HasExpired(now time.Time) bool
HasExpired reports whether certList should have been updated by now.
type Extension struct {
Id asn1.ObjectIdentifier
Critical bool `asn1:"optional"`
Value []byte
}
Extension represents the ASN.1 structure of the same name. See RFC 5280,
section 4.2.
type Name struct {
Country, Organization, OrganizationalUnit []string
Locality, Province []string
StreetAddress, PostalCode []string
SerialNumber, CommonName string
Names []AttributeTypeAndValue
ExtraNames []AttributeTypeAndValue
}
Name represents an X.509 distinguished name. This only includes the common
elements of a DN. Note that Name is only an approximation of the X.509
structure. If an accurate representation is needed, asn1.Unmarshal the raw
subject or issuer as an RDNSequence.
func (n *Name) FillFromRDNSequence(rdns *RDNSequence)
FillFromRDNSequence populates n from the provided RDNSequence. Multi-entry
RDNs are flattened, all entries are added to the relevant n fields, and the
grouping is not preserved.
func (n Name) String() string
String returns the string form of n, roughly following the RFC 2253
Distinguished Names syntax.
func (n Name) ToRDNSequence() (ret RDNSequence)
ToRDNSequence converts n into a single RDNSequence. The following attributes
are encoded as multi-value RDNs:
- Country
- Organization
- OrganizationalUnit
- Locality
- Province
- StreetAddress
- PostalCode
Each ExtraNames entry is encoded as an individual RDN.
func (n Name) appendRDNs(in RDNSequence, values []string, oid asn1.ObjectIdentifier) RDNSequence
appendRDNs appends a relativeDistinguishedNameSET to the given RDNSequence
and returns the new value. The relativeDistinguishedNameSET contains an
attributeTypeAndValue for each of the given values. See RFC 5280, A.1,
and search for AttributeTypeAndValue.
type RDNSequence []RelativeDistinguishedNameSET
func (r RDNSequence) String() string
String returns a string representation of the sequence r, roughly following
the RFC 2253 Distinguished Names syntax.
type RelativeDistinguishedNameSET []AttributeTypeAndValue
type RevokedCertificate struct {
SerialNumber *big.Int
RevocationTime time.Time
Extensions []Extension `asn1:"optional"`
}
RevokedCertificate represents the ASN.1 structure of the same name. See RFC
5280, section 5.1.
type TBSCertificateList struct {
Raw asn1.RawContent
Version int `asn1:"optional,default:0"`
Signature AlgorithmIdentifier
Issuer RDNSequence
ThisUpdate time.Time
NextUpdate time.Time `asn1:"optional"`
RevokedCertificates []RevokedCertificate `asn1:"optional"`
Extensions []Extension `asn1:"tag:0,optional,explicit"`
}
TBSCertificateList represents the ASN.1 structure of the same name. See RFC
5280, section 5.1.
Deprecated: x509.RevocationList should be used instead.
database/sql
func Drivers() []string
Drivers returns a sorted list of the names of the registered drivers.
func Register(name string, driver driver.Driver)
Register makes a database driver available by the provided name. If Register
is called twice with the same name or if driver is nil, it panics.
func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool)
func asString(src any) string
func callValuerValue(vr driver.Valuer) (v driver.Value, err error)
callValuerValue returns vr.Value(), with one exception: If vr.Value is an
auto-generated method on a pointer type and the pointer is nil, it would
panic at runtime in the panicwrap method. Treat it like nil instead.
Issue 8415.
This is so people can implement driver.Value on value types and still use
nil pointers to those types to mean nil/NULL, just like string/*string.
This function is mirrored in the database/sql/driver package.
func convertAssign(dest, src any) error
convertAssign is the same as convertAssignRows, but without the optional
rows argument.
convertAssign should be an internal detail, but widely used packages access
it using linkname. Notable members of the hall of shame include:
- ariga.io/entcache
Do not remove or change the type signature. See go.dev/issue/67401.
func convertAssignRows(dest, src any, rows *Rows) error
convertAssignRows copies to dest the value in src, converting it if
possible. An error is returned if the copy would result in loss of
information. dest should be a pointer type. If rows is passed in,
the rows will be used as the parent for any cursor values converted from a
driver.Rows to a *Rows.
func ctxDriverBegin(ctx context.Context, opts *TxOptions, ci driver.Conn) (driver.Tx, error)
func ctxDriverExec(ctx context.Context, execerCtx driver.ExecerContext, execer driver.Execer, query string, nvdargs []driver.NamedValue) (driver.Result, error)
func ctxDriverPrepare(ctx context.Context, ci driver.Conn, query string) (driver.Stmt, error)
func ctxDriverQuery(ctx context.Context, queryerCtx driver.QueryerContext, queryer driver.Queryer, query string, nvdargs []driver.NamedValue) (driver.Rows, error)
func ctxDriverStmtExec(ctx context.Context, si driver.Stmt, nvdargs []driver.NamedValue) (driver.Result, error)
func ctxDriverStmtQuery(ctx context.Context, si driver.Stmt, nvdargs []driver.NamedValue) (driver.Rows, error)
func defaultCheckNamedValue(nv *driver.NamedValue) (err error)
defaultCheckNamedValue wraps the default ColumnConverter to have the same
function signature as the CheckNamedValue in the driver.NamedValueChecker
interface.
func describeNamedValue(nv *driver.NamedValue) string
func driverArgsConnLocked(ci driver.Conn, ds *driverStmt, args []any) ([]driver.NamedValue, error)
driverArgsConnLocked converts arguments from callers of Stmt.Exec and
Stmt.Query into driver Values.
The statement ds may be nil, if no statement is available.
ci must be locked.
func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error)
func rowsiFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...any) (driver.Rows, error)
func scanArgsContainRawBytes(args []any) bool
func stack() string
func strconvErr(err error) error
func unregisterAllDrivers()
func validateNamedValueName(name string) error
func withLock(lk sync.Locker, fn func())
withLock runs while holding lk.
TYPES
type ColumnType struct {
name string
hasNullable bool
hasLength bool
hasPrecisionScale bool
nullable bool
length int64
databaseType string
precision int64
scale int64
scanType reflect.Type
}
ColumnType contains the name and type of a column.
func rowsColumnInfoSetupConnLocked(rowsi driver.Rows) []*ColumnType
func (ci *ColumnType) DatabaseTypeName() string
DatabaseTypeName returns the database system name of the column type.
If an empty string is returned, then the driver type name is not supported.
Consult your driver documentation for a list of driver data types.
ColumnType.Length specifiers are not included. Common type names include
"VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", and "BIGINT".
func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool)
DecimalSize returns the scale and precision of a decimal type. If not
applicable or if not supported ok is false.
func (ci *ColumnType) Length() (length int64, ok bool)
Length returns the column type length for variable length column types such
as text and binary field types. If the type length is unbounded the value
will be math.MaxInt64 (any database limits will still apply). If the column
type is not variable length, such as an int, or if not supported by the
driver ok is false.
func (ci *ColumnType) Name() string
Name returns the name or alias of the column.
func (ci *ColumnType) Nullable() (nullable, ok bool)
Nullable reports whether the column may be null. If a driver does not
support this property ok will be false.
func (ci *ColumnType) ScanType() reflect.Type
ScanType returns a Go type suitable for scanning into using Rows.Scan.
If a driver does not support this property ScanType will return the type of
an empty interface.
type Conn struct {
db *DB
closemu sync.RWMutex
dc *driverConn
done atomic.Bool
releaseConnOnce sync.Once
releaseConnCache releaseConn
}
Conn represents a single database connection rather than a pool of database
connections. Prefer running queries from DB unless there is a specific need
for a continuous single database connection.
A Conn must call Conn.Close to return the connection to the database pool
and may do so concurrently with a running query.
After a call to Conn.Close, all operations on the connection fail with
ErrConnDone.
func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)
BeginTx starts a transaction.
The provided context is used until the transaction is committed or rolled
back. If the context is canceled, the sql package will roll back the
transaction. Tx.Commit will return an error if the context provided to
BeginTx is canceled.
The provided TxOptions is optional and may be nil if defaults should be
used. If a non-default isolation level is used that the driver doesn't
support, an error will be returned.
func (c *Conn) Close() error
Close returns the connection to the connection pool. All operations after a
Close will return with ErrConnDone. Close is safe to call concurrently with
other operations and will block until all other operations finish. It may be
useful to first cancel any used context and then call close directly after.
func (c *Conn) ExecContext(ctx context.Context, query string, args ...any) (Result, error)
ExecContext executes a query without returning any rows. The args are for
any placeholder parameters in the query.
func (c *Conn) PingContext(ctx context.Context) error
PingContext verifies the connection to the database is still alive.
func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error)
PrepareContext creates a prepared statement for later queries or executions.
Multiple queries or executions may be run concurrently from the returned
statement. The caller must call the statement's *Stmt.Close method when the
statement is no longer needed.
The provided context is used for the preparation of the statement, not for
the execution of the statement.
func (c *Conn) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)
QueryContext executes a query that returns rows, typically a SELECT.
The args are for any placeholder parameters in the query.
func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row
QueryRowContext executes a query that is expected to return at most one row.
QueryRowContext always returns a non-nil value. Errors are deferred until
the *Row.Scan method is called. If the query selects no rows, the *Row.Scan
will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row
and discards the rest.
func (c *Conn) Raw(f func(driverConn any) error) (err error)
Raw executes f exposing the underlying driver connection for the duration of
f. The driverConn must not be used outside of f.
Once f returns and err is not driver.ErrBadConn, the Conn will continue to
be usable until Conn.Close is called.
func (c *Conn) close(err error) error
func (c *Conn) closemuRUnlockCondReleaseConn(err error)
closemuRUnlockCondReleaseConn read unlocks closemu as the sql operation is
done with the dc.
func (c *Conn) grabConn(context.Context) (*driverConn, releaseConn, error)
grabConn takes a context to implement stmtConnGrabber but the context is not
used.
func (c *Conn) txCtx() context.Context
type DB struct {
waitDuration atomic.Int64
connector driver.Connector
numClosed atomic.Uint64
connRequests connRequestSet
openerCh chan struct{}
closed bool
dep map[finalCloser]depSet
cleanerCh chan struct{}
}
DB is a database handle representing a pool of zero or more underlying
connections. It's safe for concurrent use by multiple goroutines.
The sql package creates and frees connections automatically; it also
maintains a free pool of idle connections. If the database has a concept
of per-connection state, such state can be reliably observed within a
transaction (Tx) or connection (Conn). Once DB.Begin is called, the returned
Tx is bound to a single connection. Once Tx.Commit or Tx.Rollback is called
on the transaction, that transaction's connection is returned to DB's idle
connection pool. The pool size can be controlled with DB.SetMaxIdleConns.
func Open(driverName, dataSourceName string) (*DB, error)
Open opens a database specified by its database driver name and a
driver-specific data source name, usually consisting of at least a database
name and connection information.
Most users will open a database via a driver-specific connection helper
function that returns a *DB. No database drivers are included in the
third-party drivers.
Open may just validate its arguments without creating a connection to the
database. To verify that the data source name is valid, call DB.Ping.
The returned DB is safe for concurrent use by multiple goroutines and
maintains its own pool of idle connections. Thus, the Open function should
be called just once. It is rarely necessary to close a DB.
func OpenDB(c driver.Connector) *DB
OpenDB opens a database using a driver.Connector, allowing drivers to bypass
a string based data source name.
Most users will open a database via a driver-specific connection helper
function that returns a *DB. No database drivers are included in the
third-party drivers.
OpenDB may just validate its arguments without creating a connection to the
database. To verify that the data source name is valid, call DB.Ping.
The returned DB is safe for concurrent use by multiple goroutines and
maintains its own pool of idle connections. Thus, the OpenDB function should
be called just once. It is rarely necessary to close a DB.
func (db *DB) Begin() (*Tx, error)
Begin starts a transaction. The default isolation level is dependent on the
driver.
Begin uses context.Background internally; to specify the context, use
DB.BeginTx.
func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)
BeginTx starts a transaction.
The provided context is used until the transaction is committed or rolled
back. If the context is canceled, the sql package will roll back the
transaction. Tx.Commit will return an error if the context provided to
BeginTx is canceled.
The provided TxOptions is optional and may be nil if defaults should be
used. If a non-default isolation level is used that the driver doesn't
support, an error will be returned.
func (db *DB) Close() error
Close closes the database and prevents new queries from starting. Close then
waits for all queries that have started processing on the server to finish.
It is rare to Close a DB, as the DB handle is meant to be long-lived and
shared between many goroutines.
func (db *DB) Conn(ctx context.Context) (*Conn, error)
Conn returns a single connection by either opening a new connection or
returning an existing connection from the connection pool. Conn will block
until either a connection is returned or ctx is canceled. Queries run on the
same Conn will be run in the same database session.
Every Conn must be returned to the database pool after use by calling
Conn.Close.
func (db *DB) Driver() driver.Driver
Driver returns the database's underlying driver.
func (db *DB) Exec(query string, args ...any) (Result, error)
Exec executes a query without returning any rows. The args are for any
placeholder parameters in the query.
Exec uses context.Background internally; to specify the context, use
DB.ExecContext.
func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error)
ExecContext executes a query without returning any rows. The args are for
any placeholder parameters in the query.
func (db *DB) Ping() error
Ping verifies a connection to the database is still alive, establishing a
connection if necessary.
Ping uses context.Background internally; to specify the context, use
DB.PingContext.
func (db *DB) PingContext(ctx context.Context) error
PingContext verifies a connection to the database is still alive,
establishing a connection if necessary.
func (db *DB) Prepare(query string) (*Stmt, error)
Prepare creates a prepared statement for later queries or executions.
Multiple queries or executions may be run concurrently from the returned
statement. The caller must call the statement's *Stmt.Close method when the
statement is no longer needed.
Prepare uses context.Background internally; to specify the context,
use DB.PrepareContext.
func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error)
PrepareContext creates a prepared statement for later queries or executions.
Multiple queries or executions may be run concurrently from the returned
statement. The caller must call the statement's *Stmt.Close method when the
statement is no longer needed.
The provided context is used for the preparation of the statement, not for
the execution of the statement.
func (db *DB) Query(query string, args ...any) (*Rows, error)
Query executes a query that returns rows, typically a SELECT. The args are
for any placeholder parameters in the query.
Query uses context.Background internally; to specify the context, use
DB.QueryContext.
func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)
QueryContext executes a query that returns rows, typically a SELECT.
The args are for any placeholder parameters in the query.
func (db *DB) QueryRow(query string, args ...any) *Row
QueryRow executes a query that is expected to return at most one row.
QueryRow always returns a non-nil value. Errors are deferred until Row's
Scan method is called. If the query selects no rows, the *Row.Scan will
return ErrNoRows. Otherwise, *Row.Scan scans the first selected row and
discards the rest.
QueryRow uses context.Background internally; to specify the context,
use DB.QueryRowContext.
func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row
QueryRowContext executes a query that is expected to return at most one row.
QueryRowContext always returns a non-nil value. Errors are deferred until
Row's Scan method is called. If the query selects no rows, the *Row.Scan
will return ErrNoRows. Otherwise, *Row.Scan scans the first selected row and
discards the rest.
func (db *DB) SetConnMaxIdleTime(d time.Duration)
SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.
Expired connections may be closed lazily before reuse.
If d <= 0, connections are not closed due to a connection's idle time.
func (db *DB) SetConnMaxLifetime(d time.Duration)
SetConnMaxLifetime sets the maximum amount of time a connection may be
reused.
Expired connections may be closed lazily before reuse.
If d <= 0, connections are not closed due to a connection's age.
func (db *DB) SetMaxIdleConns(n int)
SetMaxIdleConns sets the maximum number of connections in the idle
connection pool.
If MaxOpenConns is greater than 0 but less than the new MaxIdleConns,
then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.
If n <= 0, no idle connections are retained.
The default max idle connections is currently 2. This may change in a future
release.
func (db *DB) SetMaxOpenConns(n int)
SetMaxOpenConns sets the maximum number of open connections to the database.
If MaxIdleConns is greater than 0 and the new MaxOpenConns is less
than MaxIdleConns, then MaxIdleConns will be reduced to match the new
MaxOpenConns limit.
If n <= 0, then there is no limit on the number of open connections.
The default is 0 (unlimited).
func (db *DB) Stats() DBStats
Stats returns database statistics.
func (db *DB) addDep(x finalCloser, dep any)
addDep notes that x now depends on dep, and x's finalClose won't be called
until all of x's dependencies are removed with removeDep.
func (db *DB) addDepLocked(x finalCloser, dep any)
func (db *DB) begin(ctx context.Context, opts *TxOptions, strategy connReuseStrategy) (tx *Tx, err error)
func (db *DB) beginDC(ctx context.Context, dc *driverConn, release func(error), opts *TxOptions) (tx *Tx, err error)
beginDC starts a transaction. The provided dc must be valid and ready to
use.
func (db *DB) conn(ctx context.Context, strategy connReuseStrategy) (*driverConn, error)
conn returns a newly-opened or cached *driverConn.
func (db *DB) connectionCleaner(d time.Duration)
func (db *DB) connectionCleanerRunLocked(d time.Duration) (time.Duration, []*driverConn)
connectionCleanerRunLocked removes connections that should be closed from
freeConn and returns them along side an updated duration to the next
check if a quicker check is required to ensure connections are checked
appropriately.
func (db *DB) connectionOpener(ctx context.Context)
Runs in a separate goroutine, opens new connections when requested.
func (db *DB) exec(ctx context.Context, query string, args []any, strategy connReuseStrategy) (Result, error)
func (db *DB) execDC(ctx context.Context, dc *driverConn, release func(error), query string, args []any) (res Result, err error)
func (db *DB) maxIdleConnsLocked() int
func (db *DB) maybeOpenNewConnections()
Assumes db.mu is locked. If there are connRequests and the connection limit
hasn't been reached, then tell the connectionOpener to open new connections.
func (db *DB) noteUnusedDriverStatement(c *driverConn, ds *driverStmt)
noteUnusedDriverStatement notes that ds is no longer used and should be
closed whenever possible (when c is next not in use), unless c is already
closed.
func (db *DB) openNewConnection(ctx context.Context)
Open one new connection
func (db *DB) pingDC(ctx context.Context, dc *driverConn, release func(error)) error
func (db *DB) prepare(ctx context.Context, query string, strategy connReuseStrategy) (*Stmt, error)
func (db *DB) prepareDC(ctx context.Context, dc *driverConn, release func(error), cg stmtConnGrabber, query string) (*Stmt, error)
prepareDC prepares a query on the driverConn and calls release before
returning. When cg == nil it implies that a connection pool is used,
and when cg != nil only a single driver connection is used.
func (db *DB) putConn(dc *driverConn, err error, resetSession bool)
putConn adds a connection to the db's free pool. err is optionally the last
error that occurred on this connection.
func (db *DB) putConnDBLocked(dc *driverConn, err error) bool
Satisfy a connRequest or put the driverConn in the idle pool and return true
or return false. putConnDBLocked will satisfy a connRequest if there is one,
or it will return the *driverConn to the freeConn list if err == nil and the
idle connection limit will not be exceeded. If err != nil, the value of dc
is ignored. If err == nil, then dc must not equal nil. If a connRequest was
fulfilled or the *driverConn was placed in the freeConn list, then true is
returned, otherwise false is returned.
func (db *DB) query(ctx context.Context, query string, args []any, strategy connReuseStrategy) (*Rows, error)
func (db *DB) queryDC(ctx, txctx context.Context, dc *driverConn, releaseConn func(error), query string, args []any) (*Rows, error)
queryDC executes a query on the given connection. The connection gets
released by the releaseConn function. The ctx context is from a query method
and the txctx context is from an optional transaction context.
func (db *DB) removeDep(x finalCloser, dep any) error
removeDep notes that x no longer depends on dep. If x still has
dependencies, nil is returned. If x no longer has any dependencies,
its finalClose method will be called and its error value will be returned.
func (db *DB) removeDepLocked(x finalCloser, dep any) func() error
func (db *DB) retry(fn func(strategy connReuseStrategy) error) error
func (db *DB) shortestIdleTimeLocked() time.Duration
func (db *DB) startCleanerLocked()
startCleanerLocked starts connectionCleaner if needed.
type DBStats struct {
}
DBStats contains database statistics.
type IsolationLevel int
IsolationLevel is the transaction isolation level used in TxOptions.
const (
LevelDefault IsolationLevel = iota
LevelReadUncommitted
LevelReadCommitted
LevelWriteCommitted
LevelRepeatableRead
LevelSnapshot
LevelSerializable
LevelLinearizable
)
Various isolation levels that drivers may support in DB.BeginTx. If a driver
does not support a given isolation level an error may be returned.
See
func (i IsolationLevel) String() string
String returns the name of the transaction isolation level.
type NamedArg struct {
_NamedFieldsRequired struct{}
Name string
Value any
}
A NamedArg is a named argument. NamedArg values may be used as arguments to
DB.Query or DB.Exec and bind to the corresponding named parameter in the SQL
statement.
For a more concise way to create NamedArg values, see the Named function.
func Named(name string, value any) NamedArg
Named provides a more concise way to create NamedArg values.
Example usage:
db.ExecContext(ctx, `
delete from Invoice
where
TimeCreated < @end
and TimeCreated >= @start;`,
sql.Named("start", startTime),
sql.Named("end", endTime),
)
type Null[T any] struct {
V T
Valid bool
}
Null represents a value that may be null. Null implements the Scanner
interface so it can be used as a scan destination:
var s Null[string]
err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
...
if s.Valid {
} else {
}
T should be one of the types accepted by driver.Value.
func (n *Null[T]) Scan(value any) error
func (n Null[T]) Value() (driver.Value, error)
type NullBool struct {
Bool bool
}
NullBool represents a bool that may be null. NullBool implements the Scanner
interface so it can be used as a scan destination, similar to NullString.
func (n *NullBool) Scan(value any) error
Scan implements the Scanner interface.
func (n NullBool) Value() (driver.Value, error)
Value implements the driver.Valuer interface.
type NullByte struct {
Byte byte
}
NullByte represents a byte that may be null. NullByte implements the Scanner
interface so it can be used as a scan destination, similar to NullString.
func (n *NullByte) Scan(value any) error
Scan implements the Scanner interface.
func (n NullByte) Value() (driver.Value, error)
Value implements the driver.Valuer interface.
type NullFloat64 struct {
Float64 float64
}
NullFloat64 represents a float64 that may be null. NullFloat64 implements
the Scanner interface so it can be used as a scan destination, similar to
NullString.
func (n *NullFloat64) Scan(value any) error
Scan implements the Scanner interface.
func (n NullFloat64) Value() (driver.Value, error)
Value implements the driver.Valuer interface.
type NullInt16 struct {
Int16 int16
}
NullInt16 represents an int16 that may be null. NullInt16 implements the
Scanner interface so it can be used as a scan destination, similar to
NullString.
func (n *NullInt16) Scan(value any) error
Scan implements the Scanner interface.
func (n NullInt16) Value() (driver.Value, error)
Value implements the driver.Valuer interface.
type NullInt32 struct {
Int32 int32
}
NullInt32 represents an int32 that may be null. NullInt32 implements the
Scanner interface so it can be used as a scan destination, similar to
NullString.
func (n *NullInt32) Scan(value any) error
Scan implements the Scanner interface.
func (n NullInt32) Value() (driver.Value, error)
Value implements the driver.Valuer interface.
type NullInt64 struct {
Int64 int64
}
NullInt64 represents an int64 that may be null. NullInt64 implements the
Scanner interface so it can be used as a scan destination, similar to
NullString.
func (n *NullInt64) Scan(value any) error
Scan implements the Scanner interface.
func (n NullInt64) Value() (driver.Value, error)
Value implements the driver.Valuer interface.
type NullString struct {
String string
}
NullString represents a string that may be null. NullString implements the
Scanner interface so it can be used as a scan destination:
var s NullString
err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
...
if s.Valid {
} else {
}
func (ns *NullString) Scan(value any) error
Scan implements the Scanner interface.
func (ns NullString) Value() (driver.Value, error)
Value implements the driver.Valuer interface.
type NullTime struct {
Time time.Time
}
NullTime represents a time.Time that may be null. NullTime implements
the Scanner interface so it can be used as a scan destination, similar to
NullString.
func (n *NullTime) Scan(value any) error
Scan implements the Scanner interface.
func (n NullTime) Value() (driver.Value, error)
Value implements the driver.Valuer interface.
type Out struct {
_NamedFieldsRequired struct{}
Dest any
In bool
}
Out may be used to retrieve OUTPUT value parameters from stored procedures.
Not all drivers and databases support OUTPUT value parameters.
Example usage:
var outArg string
_, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg}))
type RawBytes []byte
RawBytes is a byte slice that holds a reference to memory owned by the
database itself. After a Rows.Scan into a RawBytes, the slice is only valid
until the next call to Rows.Next, Rows.Scan, or Rows.Close.
type Result interface {
LastInsertId() (int64, error)
RowsAffected() (int64, error)
}
A Result summarizes an executed SQL command.
func resultFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...any) (Result, error)
type Row struct {
rows *Rows
}
Row is the result of calling DB.QueryRow to select a single row.
func (r *Row) Err() error
Err provides a way for wrapping packages to check for query errors without
calling Row.Scan. Err returns the error, if any, that was encountered
while running the query. If this error is not nil, this error will also be
returned from Row.Scan.
func (r *Row) Scan(dest ...any) error
Scan copies the columns from the matched row into the values pointed at by
dest. See the documentation on Rows.Scan for details. If more than one row
matches the query, Scan uses the first row and discards the rest. If no row
matches the query, Scan returns ErrNoRows.
type Rows struct {
releaseConn func(error)
rowsi driver.Rows
closemu sync.RWMutex
closed bool
closemuScanHold bool
hitEOF bool
lastcols []driver.Value
raw []byte
}
Rows is the result of a query. Its cursor starts before the first row of the
result set. Use Rows.Next to advance from row to row.
func (rs *Rows) Close() error
Close closes the Rows, preventing further enumeration. If Rows.Next is
called and returns false and there are no further result sets, the Rows are
closed automatically and it will suffice to check the result of Rows.Err.
Close is idempotent and does not affect the result of Rows.Err.
func (rs *Rows) ColumnTypes() ([]*ColumnType, error)
ColumnTypes returns column information such as column type, length,
and nullable. Some information may not be available from some drivers.
func (rs *Rows) Columns() ([]string, error)
Columns returns the column names. Columns returns an error if the rows are
closed.
func (rs *Rows) Err() error
Err returns the error, if any, that was encountered during iteration.
Err may be called after an explicit or implicit Rows.Close.
func (rs *Rows) Next() bool
Next prepares the next result row for reading with the Rows.Scan method. It
returns true on success, or false if there is no next result row or an error
happened while preparing it. Rows.Err should be consulted to distinguish
between the two cases.
Every call to Rows.Scan, even the first one, must be preceded by a call to
Rows.Next.
func (rs *Rows) NextResultSet() bool
NextResultSet prepares the next result set for reading. It reports whether
there is further result sets, or false if there is no further result set
or if there is an error advancing to it. The Rows.Err method should be
consulted to distinguish between the two cases.
After calling NextResultSet, the Rows.Next method should always be called
before scanning. If there are further result sets they may not have rows in
the result set.
func (rs *Rows) Scan(dest ...any) error
Scan copies the columns in the current row into the values pointed at by
dest. The number of values in dest must be the same as the number of columns
in Rows.
Scan converts columns read from the database into the following common Go
types and special types provided by the sql package:
*string
*[]byte
*int, *int8, *int16, *int32, *int64
*uint, *uint8, *uint16, *uint32, *uint64
*bool
*float32, *float64
*interface{}
*RawBytes
*Rows (cursor value)
any type implementing Scanner (see Scanner docs)
In the most simple case, if the type of the value from the source column
is an integer, bool or string type T and dest is of type *T, Scan simply
assigns the value through the pointer.
Scan also converts between string and numeric types, as long as no
information would be lost. While Scan stringifies all numbers scanned from
numeric database columns into *string, scans into numeric types are checked
for overflow. For example, a float64 with value 300 or a string with value
"300" can scan into a uint16, but not into a uint8, though float64(255) or
"255" can scan into a uint8. One exception is that scans of some float64
numbers to strings may lose information when stringifying. In general,
scan floating point columns into *float64.
If a dest argument has type *[]byte, Scan saves in that argument a copy of
the corresponding data. The copy is owned by the caller and can be modified
and held indefinitely. The copy can be avoided by using an argument of type
*RawBytes instead; see the documentation for RawBytes for restrictions on
its use.
If an argument has type *interface{}, Scan copies the value provided by the
underlying driver without conversion. When scanning from a source value of
type []byte to *interface{}, a copy of the slice is made and the caller owns
the result.
Source values of type time.Time may be scanned into values of type
*time.Time, *interface{}, *string, or *[]byte. When converting to the latter
two, time.RFC3339Nano is used.
Source values of type bool may be scanned into types *bool, *interface{},
*string, *[]byte, or *RawBytes.
For scanning into *bool, the source may be true, false, 1, 0, or string
inputs parseable by strconv.ParseBool.
Scan can also convert a cursor returned from a query, such as "select
cursor(select * from my_table) from dual", into a *Rows value that can
itself be scanned from. The parent select query will close any cursor *Rows
if the parent *Rows is closed.
If any of the first arguments implementing Scanner returns an error,
that error will be wrapped in the returned error.
func (rs *Rows) awaitDone(ctx, txctx, closectx context.Context)
awaitDone blocks until ctx, txctx, or closectx is canceled. The ctx is
provided from the query context. If the query was issued in a transaction,
the transaction's context is also provided in txctx, to ensure Rows is
closed if the Tx is closed. The closectx is closed by an explicit call to
rs.Close.
func (rs *Rows) close(err error) error
func (rs *Rows) closemuRUnlockIfHeldByScan()
closemuRUnlockIfHeldByScan releases any closemu.RLock held open by a
previous call to Scan with *RawBytes.
func (rs *Rows) initContextClose(ctx, txctx context.Context)
func (rs *Rows) lasterrOrErrLocked(err error) error
lasterrOrErrLocked returns either lasterr or the provided err. rs.closemu
must be read-locked.
func (rs *Rows) nextLocked() (doClose, ok bool)
func (rs *Rows) rawbuf() []byte
rawbuf returns the buffer to append RawBytes values to. This buffer is
reused across calls to Rows.Scan.
Usage:
rawBytes = rows.setrawbuf(append(rows.rawbuf(), value...))
func (rs *Rows) setrawbuf(b []byte) RawBytes
setrawbuf updates the RawBytes buffer with the result of appending a new
value to it. It returns the new value.
type Scanner interface {
Scan(src any) error
}
Scanner is an interface used by Rows.Scan.
type Stmt struct {
cg stmtConnGrabber
cgds *driverStmt
parentStmt *Stmt
closed bool
css []connStmt
lastNumClosed uint64
}
Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple
goroutines.
If a Stmt is prepared on a Tx or Conn, it will be bound to a single
underlying connection forever. If the Tx or Conn closes, the Stmt will
become unusable and all operations will return an error. If a Stmt is
prepared on a DB, it will remain usable for the lifetime of the DB. When the
Stmt needs to execute on a new underlying connection, it will prepare itself
on the new connection automatically.
func (s *Stmt) Close() error
Close closes the statement.
func (s *Stmt) Exec(args ...any) (Result, error)
Exec executes a prepared statement with the given arguments and returns a
Result summarizing the effect of the statement.
Exec uses context.Background internally; to specify the context, use
Stmt.ExecContext.
func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error)
ExecContext executes a prepared statement with the given arguments and
returns a Result summarizing the effect of the statement.
func (s *Stmt) Query(args ...any) (*Rows, error)
Query executes a prepared query statement with the given arguments and
returns the query results as a *Rows.
Query uses context.Background internally; to specify the context, use
Stmt.QueryContext.
func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error)
QueryContext executes a prepared query statement with the given arguments
and returns the query results as a *Rows.
func (s *Stmt) QueryRow(args ...any) *Row
QueryRow executes a prepared query statement with the given arguments.
If an error occurs during the execution of the statement, that error will be
returned by a call to Scan on the returned *Row, which is always non-nil. If
the query selects no rows, the *Row.Scan will return ErrNoRows. Otherwise,
the *Row.Scan scans the first selected row and discards the rest.
Example usage:
var name string
err := nameByUseridStmt.QueryRow(id).Scan(&name)
QueryRow uses context.Background internally; to specify the context,
use Stmt.QueryRowContext.
func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row
QueryRowContext executes a prepared query statement with the given
arguments. If an error occurs during the execution of the statement,
that error will be returned by a call to Scan on the returned *Row,
which is always non-nil. If the query selects no rows, the *Row.Scan will
return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and
discards the rest.
func (s *Stmt) connStmt(ctx context.Context, strategy connReuseStrategy) (dc *driverConn, releaseConn func(error), ds *driverStmt, err error)
connStmt returns a free driver connection on which to execute the statement,
a function to call to release the connection, and a statement bound to that
connection.
func (s *Stmt) finalClose() error
func (s *Stmt) prepareOnConnLocked(ctx context.Context, dc *driverConn) (*driverStmt, error)
prepareOnConnLocked prepares the query in Stmt s on dc and adds it to the
list of open connStmt on the statement. It assumes the caller is holding the
lock on dc.
func (s *Stmt) removeClosedStmtLocked()
removeClosedStmtLocked removes closed conns in s.css.
To avoid lock contention on DB.mu, we do it only when s.db.numClosed -
s.lastNum is large enough.
type Tx struct {
db *DB
closemu sync.RWMutex
dc *driverConn
txi driver.Tx
releaseConn func(error)
done atomic.Bool
keepConnOnRollback bool
stmts struct {
sync.Mutex
v []*Stmt
}
cancel func()
ctx context.Context
}
Tx is an in-progress database transaction.
A transaction must end with a call to Tx.Commit or Tx.Rollback.
After a call to Tx.Commit or Tx.Rollback, all operations on the transaction
fail with ErrTxDone.
The statements prepared for a transaction by calling the transaction's
Tx.Prepare or Tx.Stmt methods are closed by the call to Tx.Commit or
Tx.Rollback.
func (tx *Tx) Commit() error
Commit commits the transaction.
func (tx *Tx) Exec(query string, args ...any) (Result, error)
Exec executes a query that doesn't return rows. For example: an INSERT and
UPDATE.
Exec uses context.Background internally; to specify the context, use
Tx.ExecContext.
func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (Result, error)
ExecContext executes a query that doesn't return rows. For example:
an INSERT and UPDATE.
func (tx *Tx) Prepare(query string) (*Stmt, error)
Prepare creates a prepared statement for use within a transaction.
The returned statement operates within the transaction and will be closed
when the transaction has been committed or rolled back.
To use an existing prepared statement on this transaction, see Tx.Stmt.
Prepare uses context.Background internally; to specify the context,
use Tx.PrepareContext.
func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error)
PrepareContext creates a prepared statement for use within a transaction.
The returned statement operates within the transaction and will be closed
when the transaction has been committed or rolled back.
To use an existing prepared statement on this transaction, see Tx.Stmt.
The provided context will be used for the preparation of the context,
not for the execution of the returned statement. The returned statement will
run in the transaction context.
func (tx *Tx) Query(query string, args ...any) (*Rows, error)
Query executes a query that returns rows, typically a SELECT.
Query uses context.Background internally; to specify the context, use
Tx.QueryContext.
func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)
QueryContext executes a query that returns rows, typically a SELECT.
func (tx *Tx) QueryRow(query string, args ...any) *Row
QueryRow executes a query that is expected to return at most one row.
QueryRow always returns a non-nil value. Errors are deferred until Row's
Scan method is called. If the query selects no rows, the *Row.Scan will
return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row and
discards the rest.
QueryRow uses context.Background internally; to specify the context,
use Tx.QueryRowContext.
func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row
QueryRowContext executes a query that is expected to return at most one row.
QueryRowContext always returns a non-nil value. Errors are deferred until
Row's Scan method is called. If the query selects no rows, the *Row.Scan
will return ErrNoRows. Otherwise, the *Row.Scan scans the first selected row
and discards the rest.
func (tx *Tx) Rollback() error
Rollback aborts the transaction.
func (tx *Tx) Stmt(stmt *Stmt) *Stmt
Stmt returns a transaction-specific prepared statement from an existing
statement.
Example:
updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
...
tx, err := db.Begin()
...
res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
The returned statement operates within the transaction and will be closed
when the transaction has been committed or rolled back.
Stmt uses context.Background internally; to specify the context, use
Tx.StmtContext.
func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt
StmtContext returns a transaction-specific prepared statement from an
existing statement.
Example:
updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
...
tx, err := db.Begin()
...
res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)
The provided context is used for the preparation of the statement, not for
the execution of the statement.
The returned statement operates within the transaction and will be closed
when the transaction has been committed or rolled back.
func (tx *Tx) awaitDone()
awaitDone blocks until the context in Tx is canceled and rolls back the
transaction if it's not already done.
func (tx *Tx) close(err error)
close returns the connection to the pool and must only be called by
Tx.rollback or Tx.Commit while tx is already canceled and won't be executed
concurrently.
func (tx *Tx) closePrepared()
Closes all Stmts prepared for this transaction.
func (tx *Tx) closemuRUnlockRelease(error)
closemuRUnlockRelease is used as a func(error) method value in
DB.ExecContext and DB.QueryContext. Unlocking in the releaseConn keeps the
driver conn from being returned to the connection pool until the Rows has
been closed.
func (tx *Tx) grabConn(ctx context.Context) (*driverConn, releaseConn, error)
func (tx *Tx) isDone() bool
func (tx *Tx) rollback(discardConn bool) error
rollback aborts the transaction and optionally forces the pool to discard
the connection.
func (tx *Tx) txCtx() context.Context
type TxOptions struct {
Isolation IsolationLevel
ReadOnly bool
}
TxOptions holds the transaction options to be used in DB.BeginTx.
type ccChecker struct {
cci driver.ColumnConverter
want int
}
ccChecker wraps the driver.ColumnConverter and allows it to be used as if it
were a NamedValueChecker. If the driver ColumnConverter is not present then
the NamedValueChecker will return driver.ErrSkip.
func (c ccChecker) CheckNamedValue(nv *driver.NamedValue) error
type connRequest struct {
conn *driverConn
err error
}
connRequest represents one request for a new connection When there are no
idle connections available, DB.conn will create a new connRequest and put it
on the db.connRequests list.
type connRequestAndIndex struct {
req chan connRequest
curIdx *int
}
type connRequestDelHandle struct {
}
connRequestDelHandle is an opaque handle to delete an item from calling Add.
type connRequestSet struct {
s []connRequestAndIndex
}
connRequestSet is a set of chan connRequest that's optimized for:
- adding an element
- removing an element (only by the caller who added it)
- taking (get + delete) a random element
We previously used a map for this but the take of a random element was
expensive, making mapiters. This type avoids a map entirely and just uses a
slice.
func (s *connRequestSet) Add(v chan connRequest) connRequestDelHandle
Add adds v to the set of waiting requests. The returned connRequestDelHandle
can be used to remove the item from the set.
func (s *connRequestSet) CloseAndRemoveAll()
CloseAndRemoveAll closes all channels in the set and clears the set.
func (s *connRequestSet) Delete(h connRequestDelHandle) bool
Delete removes an element from the set.
It reports whether the element was deleted. (It can return false if a caller
of TakeRandom took it meanwhile, or upon the second call to Delete)
func (s *connRequestSet) Len() int
Len returns the length of the set.
func (s *connRequestSet) TakeRandom() (v chan connRequest, ok bool)
TakeRandom returns and removes a random element from s and reports whether
there was one to take. (It returns ok=false if the set is empty.)
func (s *connRequestSet) deleteIndex(idx int)
type connReuseStrategy uint8
connReuseStrategy determines how (*DB).conn returns database connections.
const (
alwaysNewConn connReuseStrategy = iota
cachedOrNewConn
)
type connStmt struct {
dc *driverConn
ds *driverStmt
}
connStmt is a prepared statement on a particular connection.
type decimal interface {
decimalDecompose
decimalCompose
}
decimal composes or decomposes a decimal value to and from individual parts.
There are four parts: a boolean negative flag, a form byte with three
possible states (finite=0, infinite=1, NaN=2), a base-2 big-endian
integer coefficient (also known as a significand) as a []byte, and an
int32 exponent. These are composed into a final value as "decimal = (neg)
(form=finite) coefficient * 10 ^ exponent". A zero length coefficient is a
zero value. The big-endian integer coefficient stores the most significant
byte first (at coefficient[0]). If the form is not finite the coefficient
and exponent should be ignored. The negative parameter may be set to true
for any form, although implementations are not required to respect the
negative parameter in the non-finite form.
Implementations may choose to set the negative parameter to true on a zero
or NaN value, but implementations that do not differentiate between negative
and positive zero or NaN values should ignore the negative parameter without
error. If an implementation does not support Infinity it may be converted
into a NaN without error. If a value is set that is larger than what is
supported by an implementation, an error must be returned. Implementations
must return an error if a NaN or Infinity is attempted to be set while
neither are supported.
NOTE(kardianos): This is an experimental interface. See
type decimalCompose interface {
Compose(form byte, negative bool, coefficient []byte, exponent int32) error
}
type decimalDecompose interface {
Decompose(buf []byte) (form byte, negative bool, coefficient []byte, exponent int32)
}
depSet is a finalCloser's outstanding dependencies
type driverConn struct {
db *DB
createdAt time.Time
ci driver.Conn
closed bool
openStmt map[*driverStmt]bool
inUse bool
}
driverConn wraps a driver.Conn with a mutex, to be held during all calls
into the Conn. (including any calls onto interfaces returned via that Conn,
such as calls on Tx, Stmt, Result, Rows)
func (dc *driverConn) Close() error
func (dc *driverConn) closeDBLocked() func() error
the dc.db's Mutex is held.
func (dc *driverConn) expired(timeout time.Duration) bool
func (dc *driverConn) finalClose() error
func (dc *driverConn) prepareLocked(ctx context.Context, cg stmtConnGrabber, query string) (*driverStmt, error)
prepareLocked prepares the query on dc. When cg == nil the dc must keep
track of the prepared statements in a pool.
func (dc *driverConn) releaseConn(err error)
func (dc *driverConn) removeOpenStmt(ds *driverStmt)
func (dc *driverConn) resetSession(ctx context.Context) error
resetSession checks if the driver connection needs the session to be reset
and if required, resets it.
func (dc *driverConn) validateConnection(needsReset bool) bool
validateConnection checks if the connection is valid and can still be used.
It also marks the session for reset if required.
type driverResult struct {
resi driver.Result
}
func (dr driverResult) LastInsertId() (int64, error)
func (dr driverResult) RowsAffected() (int64, error)
type driverStmt struct {
si driver.Stmt
closed bool
}
driverStmt associates a driver.Stmt with the *driverConn from which it came,
so the driverConn's lock can be held during calls.
func (ds *driverStmt) Close() error
Close ensures driver.Stmt is only closed once and always returns the same
result.
type dsnConnector struct {
dsn string
driver driver.Driver
}
func (t dsnConnector) Connect(_ context.Context) (driver.Conn, error)
func (t dsnConnector) Driver() driver.Driver
type finalCloser interface {
finalClose() error
}
The finalCloser interface is used by (*DB).addDep and related dependency
reference counting.
type releaseConn func(error)
type stmtConnGrabber interface {
grabConn(context.Context) (*driverConn, releaseConn, error)
txCtx() context.Context
}
stmtConnGrabber represents a Tx or Conn that will return the underlying
driverConn and release function.
var (
_ stmtConnGrabber = &Tx{}
_ stmtConnGrabber = &Conn{}
)
database/sql/driver
func IsScanValue(v any) bool
IsScanValue is equivalent to IsValue. It exists for compatibility.
func IsValue(v any) bool
IsValue reports whether v is a valid Value parameter type.
TYPES
type ColumnConverter interface {
ColumnConverter(idx int) ValueConverter
}
ColumnConverter may be optionally implemented by Stmt if the statement is
aware of its own columns' types and can convert from any type to a driver
Value.
Deprecated: Drivers should implement NamedValueChecker.
type Conn interface {
Prepare(query string) (Stmt, error)
Close() error
Begin() (Tx, error)
}
Conn is a connection to a database. It is not used concurrently by multiple
goroutines.
Conn is assumed to be stateful.
type ConnBeginTx interface {
BeginTx(ctx context.Context, opts TxOptions) (Tx, error)
}
ConnBeginTx enhances the Conn interface with context and TxOptions.
type ConnPrepareContext interface {
PrepareContext(ctx context.Context, query string) (Stmt, error)
}
ConnPrepareContext enhances the Conn interface with context.
type Connector interface {
Connect(context.Context) (Conn, error)
Driver() Driver
}
A Connector represents a driver in a fixed configuration and can create any
number of equivalent Conns for use by multiple goroutines.
A Connector can be passed to database/sql.OpenDB, to allow drivers
to implement their own database/sql.DB constructors, or returned by
DriverContext's OpenConnector method, to allow drivers access to context and
to avoid repeated parsing of driver configuration.
If a Connector implements io.Closer, the database/sql.DB.Close method will
call the Close method and return error (if any).
type Driver interface {
Open(name string) (Conn, error)
}
Driver is the interface that must be implemented by a database driver.
Database drivers may implement DriverContext for access to contexts and
to parse the name only once for a pool of connections, instead of once per
connection.
type DriverContext interface {
OpenConnector(name string) (Connector, error)
}
If a Driver implements DriverContext, then database/sql.DB will call
OpenConnector to obtain a Connector and then invoke that Connector's Connect
method to obtain each needed connection, instead of invoking the Driver's
Open method for each connection. The two-step sequence allows drivers to
parse the name just once and also provides access to per-Conn contexts.
type Execer interface {
Exec(query string, args []Value) (Result, error)
}
Execer is an optional interface that may be implemented by a Conn.
If a Conn implements neither ExecerContext nor Execer, the
database/sql.DB.Exec will first prepare a query, execute the statement,
and then close the statement.
Exec may return ErrSkip.
Deprecated: Drivers should implement ExecerContext instead.
type ExecerContext interface {
ExecContext(ctx context.Context, query string, args []NamedValue) (Result, error)
}
ExecerContext is an optional interface that may be implemented by a Conn.
If a Conn does not implement ExecerContext, the database/sql.DB.Exec
will fall back to Execer; if the Conn does not implement Execer either,
database/sql.DB.Exec will first prepare a query, execute the statement,
and then close the statement.
ExecContext may return ErrSkip.
ExecContext must honor the context timeout and return when the context is
canceled.
type IsolationLevel int
IsolationLevel is the transaction isolation level stored in TxOptions.
This type should be considered identical to database/sql.IsolationLevel
along with any values defined on it.
type NamedValue struct {
Name string
Ordinal int
Value Value
}
NamedValue holds both the value name and value.
type NamedValueChecker interface {
CheckNamedValue(*NamedValue) error
}
NamedValueChecker may be optionally implemented by Conn or Stmt. It provides
the driver more control to handle Go and database types beyond the default
Value types allowed.
The database/sql package checks for value checkers in the following
order, stopping at the first found match: Stmt.NamedValueChecker,
Conn.NamedValueChecker, Stmt.ColumnConverter, DefaultParameterConverter.
If CheckNamedValue returns ErrRemoveArgument, the NamedValue will not be
included in the final query arguments. This may be used to pass special
options to the query itself.
If ErrSkip is returned the column converter error checking path is used for
the argument. Drivers may wish to return ErrSkip after they have exhausted
their own special cases.
type NotNull struct {
Converter ValueConverter
}
NotNull is a type that implements ValueConverter by disallowing nil values
but otherwise delegating to another ValueConverter.
func (n NotNull) ConvertValue(v any) (Value, error)
type Null struct {
Converter ValueConverter
}
Null is a type that implements ValueConverter by allowing nil values but
otherwise delegating to another ValueConverter.
func (n Null) ConvertValue(v any) (Value, error)
type Pinger interface {
Ping(ctx context.Context) error
}
Pinger is an optional interface that may be implemented by a Conn.
If a Conn does not implement Pinger, the database/sql.DB.Ping and
database/sql.DB.PingContext will check if there is at least one Conn
available.
If Conn.Ping returns ErrBadConn, database/sql.DB.Ping and
database/sql.DB.PingContext will remove the Conn from pool.
type Queryer interface {
Query(query string, args []Value) (Rows, error)
}
Queryer is an optional interface that may be implemented by a Conn.
If a Conn implements neither QueryerContext nor Queryer, the
database/sql.DB.Query will first prepare a query, execute the statement,
and then close the statement.
Query may return ErrSkip.
Deprecated: Drivers should implement QueryerContext instead.
type QueryerContext interface {
QueryContext(ctx context.Context, query string, args []NamedValue) (Rows, error)
}
QueryerContext is an optional interface that may be implemented by a Conn.
If a Conn does not implement QueryerContext, the database/sql.DB.Query
will fall back to Queryer; if the Conn does not implement Queryer either,
database/sql.DB.Query will first prepare a query, execute the statement,
and then close the statement.
QueryContext may return ErrSkip.
QueryContext must honor the context timeout and return when the context is
canceled.
type Result interface {
LastInsertId() (int64, error)
RowsAffected() (int64, error)
}
Result is the result of a query execution.
var _ Result = RowsAffected(0)
var _ Result = noRows{}
type Rows interface {
Columns() []string
Close() error
Next(dest []Value) error
}
Rows is an iterator over an executed query's results.
type RowsAffected int64
RowsAffected implements Result for an INSERT or UPDATE operation which
mutates a number of rows.
func (RowsAffected) LastInsertId() (int64, error)
func (v RowsAffected) RowsAffected() (int64, error)
type RowsColumnTypeDatabaseTypeName interface {
Rows
ColumnTypeDatabaseTypeName(index int) string
}
RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return
the database system type name without the length. Type names should be
uppercase. Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2",
"CHAR", "TEXT", "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT",
"JSONB", "XML", "TIMESTAMP".
type RowsColumnTypeLength interface {
Rows
ColumnTypeLength(index int) (length int64, ok bool)
}
RowsColumnTypeLength may be implemented by Rows. It should return the length
of the column type if the column is a variable length type. If the column is
not a variable length type ok should return false. If length is not limited
other than system limits, it should return math.MaxInt64. The following are
examples of returned values for various types:
TEXT (math.MaxInt64, true)
varchar(10) (10, true)
nvarchar(10) (10, true)
decimal (0, false)
int (0, false)
bytea(30) (30, true)
type RowsColumnTypeNullable interface {
Rows
ColumnTypeNullable(index int) (nullable, ok bool)
}
RowsColumnTypeNullable may be implemented by Rows. The nullable value should
be true if it is known the column may be null, or false if the column is
known to be not nullable. If the column nullability is unknown, ok should be
false.
type RowsColumnTypePrecisionScale interface {
Rows
ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool)
}
RowsColumnTypePrecisionScale may be implemented by Rows. It should return
the precision and scale for decimal types. If not applicable, ok should be
false. The following are examples of returned values for various types:
decimal(38, 4) (38, 4, true)
int (0, 0, false)
decimal (math.MaxInt64, math.MaxInt64, true)
type RowsColumnTypeScanType interface {
Rows
ColumnTypeScanType(index int) reflect.Type
}
RowsColumnTypeScanType may be implemented by Rows. It should return the
value type that can be used to scan types into. For example, the database
column type "bigint" this should return "reflect.TypeOf(int64(0))".
type RowsNextResultSet interface {
Rows
HasNextResultSet() bool
NextResultSet() error
}
RowsNextResultSet extends the Rows interface by providing a way to signal
the driver to advance to the next result set.
type SessionResetter interface {
ResetSession(ctx context.Context) error
}
SessionResetter may be implemented by Conn to allow drivers to reset the
session state associated with the connection and to signal a bad connection.
type Stmt interface {
Close() error
NumInput() int
Exec(args []Value) (Result, error)
Query(args []Value) (Rows, error)
}
Stmt is a prepared statement. It is bound to a Conn and not used by multiple
goroutines concurrently.
type StmtExecContext interface {
ExecContext(ctx context.Context, args []NamedValue) (Result, error)
}
StmtExecContext enhances the Stmt interface by providing Exec with context.
type StmtQueryContext interface {
QueryContext(ctx context.Context, args []NamedValue) (Rows, error)
}
StmtQueryContext enhances the Stmt interface by providing Query with
context.
type Tx interface {
Commit() error
Rollback() error
}
Tx is a transaction.
type TxOptions struct {
Isolation IsolationLevel
ReadOnly bool
}
TxOptions holds the transaction options.
This type should be considered identical to database/sql.TxOptions.
type Validator interface {
IsValid() bool
}
Validator may be implemented by Conn to allow drivers to signal if a
connection is valid or if it should be discarded.
If implemented, drivers may return the underlying error from queries,
even if the connection should be discarded by the connection pool.
type Value any
Value is a value that drivers must be able to handle. It is either nil,
a type handled by a database driver's NamedValueChecker interface, or an
instance of one of these types:
int64
float64
bool
[]byte
string
time.Time
If the driver supports cursors, a returned Value may also implement the
Rows interface in this package. This is used, for example, when a user
selects a cursor such as "select cursor(select * from my_table) from dual".
If the Rows from the select is closed, the cursor Rows will also be closed.
func callValuerValue(vr Valuer) (v Value, err error)
callValuerValue returns vr.Value(), with one exception: If vr.Value is an
auto-generated method on a pointer type and the pointer is nil, it would
panic at runtime in the panicwrap method. Treat it like nil instead.
Issue 8415.
This is so people can implement driver.Value on value types and still use
nil pointers to those types to mean nil/NULL, just like string/*string.
This function is mirrored in the database/sql package.
type ValueConverter interface {
ConvertValue(v any) (Value, error)
}
ValueConverter is the interface providing the ConvertValue method.
Various implementations of ValueConverter are provided by the driver package
to provide consistent implementations of conversions between drivers.
The ValueConverters have several uses:
- converting from the Value types as provided by the sql package into a
database table's specific column type and making sure it fits, such as
making sure a particular int64 fits in a table's uint16 column.
- converting a value as given from the database into one of the driver
Value types.
- by the database/sql package, for converting from a driver's Value type
to a user's type in a scan.
var _ ValueConverter = boolType{}
var _ ValueConverter = int32Type{}
var _ ValueConverter = defaultConverter{}
type Valuer interface {
Value() (Value, error)
}
Valuer is the interface providing the Value method.
Errors returned by the Value method are wrapped by the database/sql
package. This allows callers to use errors.Is for precise error
handling after operations like database/sql.Query, database/sql.Exec,
or database/sql.QueryRow.
Types implementing Valuer interface are able to convert themselves to a
driver Value.
type boolType struct{}
var Bool boolType
Bool is a ValueConverter that converts input values to bool.
The conversion rules are:
- booleans are returned unchanged
- for integer types, 1 is true 0 is false, other integers are an error
- for strings and []byte, same rules as strconv.ParseBool
- all other types are an error
func (boolType) ConvertValue(src any) (Value, error)
func (boolType) String() string
type decimalDecompose interface {
Decompose(buf []byte) (form byte, negative bool, coefficient []byte, exponent int32)
}
type defaultConverter struct{}
var DefaultParameterConverter defaultConverter
DefaultParameterConverter is the default implementation of ValueConverter
that's used when a Stmt doesn't implement ColumnConverter.
DefaultParameterConverter returns its argument directly if IsValue(arg).
Otherwise, if the argument implements Valuer, its Value method is used to
return a Value. As a fallback, the provided argument's underlying type
is used to convert it to a Value: underlying integer types are converted
to int64, floats to float64, bool, string, and []byte to themselves.
If the argument is a nil pointer, defaultConverter.ConvertValue returns
a nil Value. If the argument is a non-nil pointer, it is dereferenced and
defaultConverter.ConvertValue is called recursively. Other types are an
error.
func (defaultConverter) ConvertValue(v any) (Value, error)
type int32Type struct{}
var Int32 int32Type
Int32 is a ValueConverter that converts input values to int64, respecting
the limits of an int32 value.
func (int32Type) ConvertValue(v any) (Value, error)
type noRows struct{}
var ResultNoRows noRows
ResultNoRows is a pre-defined Result for drivers to return when a DDL
command (such as a CREATE TABLE) succeeds. It returns an error for both
LastInsertId and RowsAffected.
func (noRows) LastInsertId() (int64, error)
func (noRows) RowsAffected() (int64, error)
type stringType struct{}
var String stringType
String is a ValueConverter that converts its input to a string. If the value
is already a string or []byte, it's unchanged. If the value is of another
type, conversion to string is done with fmt.Sprintf("%v", v).
func (stringType) ConvertValue(v any) (Value, error)
debug/buildinfo
func decodeString(x exe, addr uint64) (string, uint64, error)
func hasPlan9Magic(magic []byte) bool
func readData(x exe, addr, size uint64) ([]byte, error)
func readDataInto(x exe, addr uint64, b []byte) (int, error)
func readRawBuildInfo(r io.ReaderAt) (vers, mod string, err error)
readRawBuildInfo extracts the Go toolchain version and module information
strings from a Go binary. On success, vers should be non-empty. mod is empty
if the binary was not built with modules enabled.
func readString(x exe, ptrSize int, readPtr func([]byte) uint64, addr uint64) string
readString returns the string at address addr in the executable x.
func searchMagic(x exe, start, size uint64) (uint64, error)
searchMagic returns the aligned first instance of buildInfoMagic in the data
range [addr, addr+size). Returns false if not found.
TYPES
type BuildInfo = debug.BuildInfo
Type alias for build info. We cannot move the types here, since
runtime/debug would need to import this package, which would make it a much
larger dependency.
func Read(r io.ReaderAt) (*BuildInfo, error)
Read returns build information embedded in a Go binary file accessed through
the given ReaderAt. Most information is only available for binaries built
with module support.
func ReadFile(name string) (info *BuildInfo, err error)
ReadFile returns build information embedded in a Go binary file at the given
path. Most information is only available for binaries built with module
support.
type elfExe struct {
f *elf.File
}
elfExe is the ELF implementation of the exe interface.
func (x *elfExe) DataReader(addr uint64) (io.ReaderAt, error)
func (x *elfExe) DataStart() (uint64, uint64)
type exe interface {
DataStart() (uint64, uint64)
DataReader(addr uint64) (io.ReaderAt, error)
}
type machoExe struct {
f *macho.File
}
machoExe is the Mach-O (Apple macOS/iOS) implementation of the exe
interface.
func (x *machoExe) DataReader(addr uint64) (io.ReaderAt, error)
func (x *machoExe) DataStart() (uint64, uint64)
type peExe struct {
f *pe.File
}
peExe is the PE (Windows Portable Executable) implementation of the exe
interface.
func (x *peExe) DataReader(addr uint64) (io.ReaderAt, error)
func (x *peExe) DataStart() (uint64, uint64)
func (x *peExe) imageBase() uint64
type plan9objExe struct {
f *plan9obj.File
}
plan9objExe is the Plan 9 a.out implementation of the exe interface.
func (x *plan9objExe) DataReader(addr uint64) (io.ReaderAt, error)
func (x *plan9objExe) DataStart() (uint64, uint64)
type xcoffExe struct {
f *xcoff.File
}
xcoffExe is the XCOFF (AIX eXtended COFF) implementation of the exe
interface.
func (x *xcoffExe) DataReader(addr uint64) (io.ReaderAt, error)
func (x *xcoffExe) DataStart() (uint64, uint64)
debug/dwarf
func _()
func pathIsAbs(path string) bool
pathIsAbs reports whether path is an absolute path (or "full path name" in
DWARF parlance). This is in "whatever form makes sense for the host system",
so this accepts both UNIX-style and DOS-style absolute paths. We avoid the
filepath package because we want this to behave the same regardless of our
host system and because we don't know what system the paths came from.
func pathJoin(dirname, filename string) string
pathJoin joins dirname and filename. filename must be relative. DWARF paths
can be UNIX-style or DOS-style, so this handles both.
func splitDrive(path string) (drive, rest string)
splitDrive splits the DOS drive letter or UNC share point from path, if any.
path == drive + rest
func zeroArray(t *Type)
TYPES
type AddrType struct {
BasicType
}
An AddrType represents a machine address type.
type ArrayType struct {
CommonType
Type Type
}
An ArrayType represents a fixed size array type.
func (t *ArrayType) Size() int64
func (t *ArrayType) String() string
type Attr uint32
An Attr identifies the attribute type in a DWARF [Entry.Field].
const (
AttrSibling Attr = 0x01
AttrLocation Attr = 0x02
AttrName Attr = 0x03
AttrOrdering Attr = 0x09
AttrByteSize Attr = 0x0B
AttrBitOffset Attr = 0x0C
AttrBitSize Attr = 0x0D
AttrStmtList Attr = 0x10
AttrLowpc Attr = 0x11
AttrHighpc Attr = 0x12
AttrLanguage Attr = 0x13
AttrDiscr Attr = 0x15
AttrDiscrValue Attr = 0x16
AttrVisibility Attr = 0x17
AttrImport Attr = 0x18
AttrStringLength Attr = 0x19
AttrCommonRef Attr = 0x1A
AttrCompDir Attr = 0x1B
AttrConstValue Attr = 0x1C
AttrContainingType Attr = 0x1D
AttrDefaultValue Attr = 0x1E
AttrInline Attr = 0x20
AttrIsOptional Attr = 0x21
AttrLowerBound Attr = 0x22
AttrProducer Attr = 0x25
AttrPrototyped Attr = 0x27
AttrReturnAddr Attr = 0x2A
AttrStartScope Attr = 0x2C
AttrStrideSize Attr = 0x2E
AttrUpperBound Attr = 0x2F
AttrAbstractOrigin Attr = 0x31
AttrAccessibility Attr = 0x32
AttrAddrClass Attr = 0x33
AttrArtificial Attr = 0x34
AttrBaseTypes Attr = 0x35
AttrCalling Attr = 0x36
AttrCount Attr = 0x37
AttrDataMemberLoc Attr = 0x38
AttrDeclColumn Attr = 0x39
AttrDeclFile Attr = 0x3A
AttrDeclLine Attr = 0x3B
AttrDeclaration Attr = 0x3C
AttrDiscrList Attr = 0x3D
AttrEncoding Attr = 0x3E
AttrExternal Attr = 0x3F
AttrFrameBase Attr = 0x40
AttrFriend Attr = 0x41
AttrIdentifierCase Attr = 0x42
AttrMacroInfo Attr = 0x43
AttrNamelistItem Attr = 0x44
AttrPriority Attr = 0x45
AttrSegment Attr = 0x46
AttrSpecification Attr = 0x47
AttrStaticLink Attr = 0x48
AttrType Attr = 0x49
AttrUseLocation Attr = 0x4A
AttrVarParam Attr = 0x4B
AttrVirtuality Attr = 0x4C
AttrVtableElemLoc Attr = 0x4D
AttrAllocated Attr = 0x4E
AttrAssociated Attr = 0x4F
AttrDataLocation Attr = 0x50
AttrStride Attr = 0x51
AttrEntrypc Attr = 0x52
AttrUseUTF8 Attr = 0x53
AttrExtension Attr = 0x54
AttrRanges Attr = 0x55
AttrTrampoline Attr = 0x56
AttrCallColumn Attr = 0x57
AttrCallFile Attr = 0x58
AttrCallLine Attr = 0x59
AttrDescription Attr = 0x5A
AttrBinaryScale Attr = 0x5B
AttrDecimalScale Attr = 0x5C
AttrSmall Attr = 0x5D
AttrDecimalSign Attr = 0x5E
AttrDigitCount Attr = 0x5F
AttrPictureString Attr = 0x60
AttrMutable Attr = 0x61
AttrThreadsScaled Attr = 0x62
AttrExplicit Attr = 0x63
AttrObjectPointer Attr = 0x64
AttrEndianity Attr = 0x65
AttrElemental Attr = 0x66
AttrPure Attr = 0x67
AttrRecursive Attr = 0x68
AttrSignature Attr = 0x69
AttrMainSubprogram Attr = 0x6A
AttrDataBitOffset Attr = 0x6B
AttrConstExpr Attr = 0x6C
AttrEnumClass Attr = 0x6D
AttrLinkageName Attr = 0x6E
AttrStringLengthBitSize Attr = 0x6F
AttrStringLengthByteSize Attr = 0x70
AttrRank Attr = 0x71
AttrStrOffsetsBase Attr = 0x72
AttrAddrBase Attr = 0x73
AttrRnglistsBase Attr = 0x74
AttrDwoName Attr = 0x76
AttrReference Attr = 0x77
AttrRvalueReference Attr = 0x78
AttrMacros Attr = 0x79
AttrCallAllCalls Attr = 0x7A
AttrCallAllSourceCalls Attr = 0x7B
AttrCallAllTailCalls Attr = 0x7C
AttrCallReturnPC Attr = 0x7D
AttrCallValue Attr = 0x7E
AttrCallOrigin Attr = 0x7F
AttrCallParameter Attr = 0x80
AttrCallPC Attr = 0x81
AttrCallTailCall Attr = 0x82
AttrCallTarget Attr = 0x83
AttrCallTargetClobbered Attr = 0x84
AttrCallDataLocation Attr = 0x85
AttrCallDataValue Attr = 0x86
AttrNoreturn Attr = 0x87
AttrAlignment Attr = 0x88
AttrExportSymbols Attr = 0x89
AttrDeleted Attr = 0x8A
AttrDefaulted Attr = 0x8B
AttrLoclistsBase Attr = 0x8C
)
func (a Attr) GoString() string
func (i Attr) String() string
type BasicType struct {
CommonType
BitSize int64
BitOffset int64
DataBitOffset int64
}
A BasicType holds fields common to all basic types.
See the documentation for StructField for more info on the interpretation of
the BitSize/BitOffset/DataBitOffset fields.
func (b *BasicType) Basic() *BasicType
func (t *BasicType) String() string
type BoolType struct {
BasicType
}
A BoolType represents a boolean type.
type CharType struct {
BasicType
}
A CharType represents a signed character type.
type Class int
A Class is the DWARF 4 class of an attribute value.
In general, a given attribute's value may take on one of several possible
classes defined by DWARF, each of which leads to a slightly different
interpretation of the attribute.
DWARF version 4 distinguishes attribute value classes more finely than
previous versions of DWARF. The reader will disambiguate coarser classes
from earlier versions of DWARF into the appropriate DWARF 4 class.
For example, DWARF 2 uses "constant" for constants as well as all types
of section offsets, but the reader will canonicalize attributes in DWARF
2 files that refer to section offsets to one of the Class*Ptr classes,
even though these classes were only defined in DWARF 3.
const (
ClassUnknown Class = iota
ClassAddress
ClassBlock
ClassConstant
ClassExprLoc
ClassFlag
ClassLinePtr
ClassLocListPtr
ClassMacPtr
ClassRangeListPtr
ClassReference
ClassReferenceSig
ClassString
ClassReferenceAlt
ClassStringAlt
ClassAddrPtr
ClassLocList
ClassRngList
ClassRngListsPtr
ClassStrOffsetsPtr
)
func formToClass(form format, attr Attr, vers int, b *buf) Class
formToClass returns the DWARF 4 Class for the given form. If the DWARF
version is less then 4, it will disambiguate some forms depending on the
attribute.
func (i Class) GoString() string
func (i Class) String() string
type CommonType struct {
}
A CommonType holds fields common to multiple types. If a field is not known
or not applicable for a given type, the zero value is used.
func (c *CommonType) Common() *CommonType
func (c *CommonType) Size() int64
type ComplexType struct {
BasicType
}
A ComplexType represents a complex floating point type.
type Data struct {
abbrev []byte
aranges []byte
frame []byte
info []byte
line []byte
pubnames []byte
ranges []byte
str []byte
addr []byte
lineStr []byte
strOffsets []byte
rngLists []byte
abbrevCache map[uint64]abbrevTable
bigEndian bool
order binary.ByteOrder
typeCache map[Offset]Type
typeSigs map[uint64]*typeUnit
unit []unit
}
Data represents the DWARF debugging information loaded from an executable
file (for example, an ELF or Mach-O executable).
func New(abbrev, aranges, frame, info, line, pubnames, ranges, str []byte) (*Data, error)
New returns a new Data object initialized from the given parameters. Rather
than calling this function directly, clients should typically use the DWARF
method of the File type of the appropriate package debug/elf, debug/macho,
or debug/pe.
The []byte arguments are the data from the corresponding debug section in
the object file; for example, for an ELF object, abbrev is the contents of
the ".debug_abbrev" section.
func (d *Data) AddSection(name string, contents []byte) error
AddSection adds another DWARF section by name. The name should be a DWARF
section name such as ".debug_addr", ".debug_str_offsets", and so forth.
This approach is used for new DWARF sections added in DWARF 5 and later.
func (d *Data) AddTypes(name string, types []byte) error
AddTypes will add one .debug_types section to the DWARF data. A typical
object with DWARF version 4 debug info will have multiple .debug_types
sections. The name is used for error reporting only, and serves to
distinguish one .debug_types section from another.
func (d *Data) LineReader(cu *Entry) (*LineReader, error)
LineReader returns a new reader for the line table of compilation unit cu,
which must be an Entry with tag TagCompileUnit.
If this compilation unit has no line table, it returns nil, nil.
func (d *Data) Ranges(e *Entry) ([][2]uint64, error)
Ranges returns the PC ranges covered by e, a slice of [low,high) pairs. Only
some entry types, such as TagCompileUnit or TagSubprogram, have PC ranges;
for others, this will return nil with no error.
func (d *Data) Reader() *Reader
Reader returns a new Reader for Data. The reader is positioned at byte
offset 0 in the DWARF “info” section.
func (d *Data) Type(off Offset) (Type, error)
Type reads the type at off in the DWARF “info” section.
func (d *Data) baseAddressForEntry(e *Entry) (*Entry, uint64, error)
baseAddressForEntry returns the initial base address to be used when
looking up the range list of entry e. DWARF specifies that this should be
the lowpc attribute of the enclosing compilation unit, however comments in
gdb/dwarf2read.c say that some versions of GCC use the entrypc attribute,
so we check that too.
func (d *Data) debugAddr(format dataFormat, addrBase, idx uint64) (uint64, error)
debugAddr returns the address at idx in debug_addr
func (d *Data) dwarf2Ranges(u *unit, base uint64, ranges int64, ret [][2]uint64) ([][2]uint64, error)
func (d *Data) dwarf5Ranges(u *unit, cu *Entry, base uint64, ranges int64, ret [][2]uint64) ([][2]uint64, error)
dwarf5Ranges interprets a debug_rnglists sequence, see DWARFv5 section
2.17.3 (page 53).
func (d *Data) offsetToUnit(off Offset) int
offsetToUnit returns the index of the unit containing offset off. It returns
-1 if no unit contains this offset.
func (d *Data) parseAbbrev(off uint64, vers int) (abbrevTable, error)
parseAbbrev returns the abbreviation table that starts at byte off in the
.debug_abbrev section.
func (d *Data) parseTypes(name string, types []byte) error
Parse a .debug_types section.
func (d *Data) parseUnits() ([]unit, error)
func (d *Data) readType(name string, r typeReader, off Offset, typeCache map[Offset]Type, fixups *typeFixer) (Type, error)
readType reads a type from r at off of name. It adds types to the type
cache, appends new typedef types to typedefs, and computes the sizes of
types. Callers should pass nil for typedefs; this is used for internal
recursion.
func (d *Data) sigToType(sig uint64) (Type, error)
Return the type for a type signature.
type DecodeError struct {
Name string
Offset Offset
Err string
}
func (e DecodeError) Error() string
type DotDotDotType struct {
CommonType
}
A DotDotDotType represents the variadic ... function parameter.
func (t *DotDotDotType) String() string
type Entry struct {
Field []Field
}
An entry is a sequence of attribute/value pairs.
func (e *Entry) AttrField(a Attr) *Field
AttrField returns the Field associated with attribute Attr in Entry,
or nil if there is no such attribute.
func (e *Entry) Val(a Attr) any
Val returns the value associated with attribute Attr in Entry, or nil if
there is no such attribute.
A common idiom is to merge the check for nil return with the check that the
value has the expected dynamic type, as in:
v, ok := e.Val(AttrSibling).(int64)
type EnumType struct {
CommonType
EnumName string
Val []*EnumValue
}
An EnumType represents an enumerated type. The only indication of its native
integer type is its ByteSize (inside CommonType).
func (t *EnumType) String() string
type EnumValue struct {
Name string
Val int64
}
An EnumValue represents a single enumeration value.
type Field struct {
Attr Attr
Val any
Class Class
}
A Field is a single attribute/value pair in an Entry.
A value can be one of several "attribute classes" defined by DWARF. The Go
types corresponding to each class are:
DWARF class Go type Class
----------- ------- -----
address uint64 ClassAddress
block []byte ClassBlock
constant int64 ClassConstant
flag bool ClassFlag
reference
to info dwarf.Offset ClassReference
to type unit uint64 ClassReferenceSig
string string ClassString
exprloc []byte ClassExprLoc
lineptr int64 ClassLinePtr
loclistptr int64 ClassLocListPtr
macptr int64 ClassMacPtr
rangelistptr int64 ClassRangeListPtr
For unrecognized or vendor-defined attributes, Class may be ClassUnknown.
type FloatType struct {
BasicType
}
A FloatType represents a floating point type.
type FuncType struct {
CommonType
ReturnType Type
ParamType []Type
}
A FuncType represents a function type.
func (t *FuncType) String() string
type IntType struct {
BasicType
}
An IntType represents a signed integer type.
type LineEntry struct {
Address uint64
OpIndex int
File *LineFile
Line int
Column int
IsStmt bool
BasicBlock bool
PrologueEnd bool
EpilogueBegin bool
ISA int
Discriminator int
EndSequence bool
}
A LineEntry is a row in a DWARF line table.
type LineFile struct {
Name string
}
A LineFile is a source file referenced by a DWARF line table entry.
type LineReader struct {
buf buf
section []byte
version uint16
addrsize int
segmentSelectorSize int
minInstructionLength int
maxOpsPerInstruction int
defaultIsStmt bool
lineBase int
lineRange int
opcodeBase int
opcodeLengths []int
directories []string
fileEntries []*LineFile
}
A LineReader reads a sequence of LineEntry structures from a DWARF "line"
section for a single compilation unit. LineEntries occur in order of
increasing PC and each LineEntry gives metadata for the instructions from
that LineEntry's PC to just before the next LineEntry's PC. The last entry
will have the [LineEntry.EndSequence] field set.
func (r *LineReader) Files() []*LineFile
Files returns the file name table of this compilation unit as of the current
position in the line table. The file name table may be referenced from
attributes in this compilation unit such as AttrDeclFile.
Entry 0 is always nil, since file index 0 represents "no file".
The file name table of a compilation unit is not fixed. Files returns the
file table as of the current position in the line table. This may contain
more entries than the file table at an earlier position in the line table,
though existing entries never change.
func (r *LineReader) Next(entry *LineEntry) error
Next sets *entry to the next row in this line table and moves to the next
row. If there are no more entries and the line table is properly terminated,
it returns io.EOF.
Rows are always in order of increasing entry.Address, but entry.Line may go
forward or backward.
func (r *LineReader) Reset()
Reset repositions the line table reader at the beginning of the line table.
func (r *LineReader) Seek(pos LineReaderPos)
Seek restores the line table reader to a position returned by
LineReader.Tell.
The argument pos must have been returned by a call to LineReader.Tell on
this line table.
func (r *LineReader) SeekPC(pc uint64, entry *LineEntry) error
SeekPC sets *entry to the LineEntry that includes pc and positions the
reader on the next entry in the line table. If necessary, this will seek
backwards to find pc.
If pc is not covered by any entry in this line table, SeekPC returns
ErrUnknownPC. In this case, *entry and the final seek position are
unspecified.
Note that DWARF line tables only permit sequential, forward scans. Hence,
in the worst case, this takes time linear in the size of the line table.
If the caller wishes to do repeated fast PC lookups, it should build an
appropriate index of the line table.
func (r *LineReader) Tell() LineReaderPos
Tell returns the current position in the line table.
func (r *LineReader) advancePC(opAdvance int)
advancePC advances "operation pointer" (the combination of Address and
OpIndex) in r.state by opAdvance steps.
func (r *LineReader) readFileEntry() (bool, error)
readFileEntry reads a file entry from either the header or a
DW_LNE_define_file extended opcode and adds it to r.fileEntries. A true
return value indicates that there are no more entries to read.
func (r *LineReader) readHeader(compDir string) error
readHeader reads the line number program header from r.buf and sets all of
the header fields in r.
func (r *LineReader) readLNCT(s []lnctForm, dwarf64 bool) (path string, mtime uint64, size uint64, err error)
readLNCT reads a sequence of LNCT entries and returns path information.
func (r *LineReader) readLNCTFormat() []lnctForm
readLNCTFormat reads an LNCT format description.
func (r *LineReader) resetState()
resetState resets r.state to its default values
func (r *LineReader) step(entry *LineEntry) bool
step processes the next opcode and updates r.state. If the opcode emits a
row in the line table, this updates *entry and returns true.
func (r *LineReader) updateFile()
updateFile updates r.state.File after r.fileIndex has changed or
r.fileEntries has changed.
type LineReaderPos struct {
off Offset
numFileEntries int
state LineEntry
fileIndex int
}
A LineReaderPos represents a position in a line table.
type Offset uint32
An Offset represents the location of an Entry within the DWARF info.
(See Reader.Seek.)
type PtrType struct {
CommonType
Type Type
}
A PtrType represents a pointer type.
func (t *PtrType) String() string
type QualType struct {
CommonType
Qual string
Type Type
}
A QualType represents a type that has the C/C++ "const", "restrict",
or "volatile" qualifier.
func (t *QualType) Size() int64
func (t *QualType) String() string
type Reader struct {
b buf
d *Data
err error
unit int
}
A Reader allows reading Entry structures from a DWARF “info” section.
The Entry structures are arranged in a tree. The Reader.Next function return
successive entries from a pre-order traversal of the tree. If an entry
has children, its Children field will be true, and the children follow,
terminated by an Entry with Tag 0.
func (r *Reader) AddressSize() int
AddressSize returns the size in bytes of addresses in the current
compilation unit.
func (r *Reader) ByteOrder() binary.ByteOrder
ByteOrder returns the byte order in the current compilation unit.
func (r *Reader) Next() (*Entry, error)
Next reads the next entry from the encoded entry stream. It returns nil,
nil when it reaches the end of the section. It returns an error if the
current offset is invalid or the data at the offset cannot be decoded as a
valid Entry.
func (r *Reader) Seek(off Offset)
Seek positions the Reader at offset off in the encoded entry stream.
Offset 0 can be used to denote the first entry.
func (r *Reader) SeekPC(pc uint64) (*Entry, error)
SeekPC returns the Entry for the compilation unit that includes pc, and
positions the reader to read the children of that unit. If pc is not covered
by any unit, SeekPC returns ErrUnknownPC and the position of the reader is
undefined.
Because compilation units can describe multiple regions of the executable,
in the worst case SeekPC must search through all the ranges in all the
compilation units. Each call to SeekPC starts the search at the compilation
unit of the last call, so in general looking up a series of PCs will be
faster if they are sorted. If the caller wishes to do repeated fast PC
lookups, it should build an appropriate index using the Ranges method.
func (r *Reader) SkipChildren()
SkipChildren skips over the child entries associated with the last Entry
returned by Reader.Next. If that Entry did not have children or Reader.Next
has not been called, SkipChildren is a no-op.
func (r *Reader) clone() typeReader
clone returns a copy of the reader. This is used by the typeReader
interface.
func (r *Reader) maybeNextUnit()
maybeNextUnit advances to the next unit if this one is finished.
func (r *Reader) nextUnit()
nextUnit advances to the next unit.
func (r *Reader) offset() Offset
offset returns the current buffer offset. This is used by the typeReader
interface.
type StructField struct {
Name string
Type Type
ByteOffset int64
BitOffset int64
DataBitOffset int64
}
A StructField represents a field in a struct, union, or C++ class type.
# Bit Fields
The BitSize, BitOffset, and DataBitOffset fields describe the bit size and
offset of data members declared as bit fields in C/C++ struct/union/class
types.
BitSize is the number of bits in the bit field.
DataBitOffset, if non-zero, is the number of bits from the start of the
enclosing entity (e.g. containing struct/class/union) to the start of the
bit field. This corresponds to the DW_AT_data_bit_offset DWARF attribute
that was introduced in DWARF 4.
BitOffset, if non-zero, is the number of bits between the most significant
bit of the storage unit holding the bit field to the most significant
bit of the bit field. Here "storage unit" is the type name before the
bit field (for a field "unsigned x:17", the storage unit is "unsigned").
BitOffset values can vary depending on the endianness of the system.
BitOffset corresponds to the DW_AT_bit_offset DWARF attribute that was
deprecated in DWARF 4 and removed in DWARF 5.
At most one of DataBitOffset and BitOffset will be non-zero;
DataBitOffset/BitOffset will only be non-zero if BitSize is non-zero.
Whether a C compiler uses one or the other will depend on compiler vintage
and command line options.
Here is an example of C/C++ bit field use, along with what to expect in
terms of DWARF bit offset info. Consider this code:
struct S {
int q;
int j:5;
int k:6;
int m:5;
int n:8;
} s;
For the code above, one would expect to see the following for
DW_AT_bit_offset values (using GCC 8):
Little | Big
Endian | Endian
|
"j": 27 | 0
"k": 21 | 5
"m": 16 | 11
"n": 8 | 16
Note that in the above the offsets are purely with respect to the containing
storage unit for j/k/m/n -- these values won't vary based on the size of
prior data members in the containing struct.
If the compiler emits DW_AT_data_bit_offset, the expected values would be:
"j": 32
"k": 37
"m": 43
"n": 48
Here the value 32 for "j" reflects the fact that the bit field is preceded
by other data members (recall that DW_AT_data_bit_offset values are relative
to the start of the containing struct). Hence DW_AT_data_bit_offset values
can be quite large for structs with many fields.
DWARF also allow for the possibility of base types that have non-zero bit
size and bit offset, so this information is also captured for base types,
but it is worth noting that it is not possible to trigger this behavior
using mainstream languages.
func (f *StructField) bitOffset() int64
type StructType struct {
CommonType
StructName string
Field []*StructField
}
A StructType represents a struct, union, or C++ class type.
func (t *StructType) Defn() string
func (t *StructType) String() string
type Tag uint32
A Tag is the classification (the type) of an Entry.
const (
TagArrayType Tag = 0x01
TagClassType Tag = 0x02
TagEntryPoint Tag = 0x03
TagEnumerationType Tag = 0x04
TagFormalParameter Tag = 0x05
TagImportedDeclaration Tag = 0x08
TagLabel Tag = 0x0A
TagLexDwarfBlock Tag = 0x0B
TagMember Tag = 0x0D
TagPointerType Tag = 0x0F
TagReferenceType Tag = 0x10
TagCompileUnit Tag = 0x11
TagStringType Tag = 0x12
TagStructType Tag = 0x13
TagSubroutineType Tag = 0x15
TagTypedef Tag = 0x16
TagUnionType Tag = 0x17
TagUnspecifiedParameters Tag = 0x18
TagVariant Tag = 0x19
TagCommonDwarfBlock Tag = 0x1A
TagCommonInclusion Tag = 0x1B
TagInheritance Tag = 0x1C
TagInlinedSubroutine Tag = 0x1D
TagModule Tag = 0x1E
TagPtrToMemberType Tag = 0x1F
TagSetType Tag = 0x20
TagSubrangeType Tag = 0x21
TagWithStmt Tag = 0x22
TagAccessDeclaration Tag = 0x23
TagBaseType Tag = 0x24
TagCatchDwarfBlock Tag = 0x25
TagConstType Tag = 0x26
TagConstant Tag = 0x27
TagEnumerator Tag = 0x28
TagFileType Tag = 0x29
TagFriend Tag = 0x2A
TagNamelist Tag = 0x2B
TagNamelistItem Tag = 0x2C
TagPackedType Tag = 0x2D
TagSubprogram Tag = 0x2E
TagTemplateTypeParameter Tag = 0x2F
TagTemplateValueParameter Tag = 0x30
TagThrownType Tag = 0x31
TagTryDwarfBlock Tag = 0x32
TagVariantPart Tag = 0x33
TagVariable Tag = 0x34
TagVolatileType Tag = 0x35
TagDwarfProcedure Tag = 0x36
TagRestrictType Tag = 0x37
TagInterfaceType Tag = 0x38
TagNamespace Tag = 0x39
TagImportedModule Tag = 0x3A
TagUnspecifiedType Tag = 0x3B
TagPartialUnit Tag = 0x3C
TagImportedUnit Tag = 0x3D
TagCondition Tag = 0x3F
TagSharedType Tag = 0x40
TagTypeUnit Tag = 0x41
TagRvalueReferenceType Tag = 0x42
TagTemplateAlias Tag = 0x43
TagCoarrayType Tag = 0x44
TagGenericSubrange Tag = 0x45
TagDynamicType Tag = 0x46
TagAtomicType Tag = 0x47
TagCallSite Tag = 0x48
TagCallSiteParameter Tag = 0x49
TagSkeletonUnit Tag = 0x4A
TagImmutableType Tag = 0x4B
)
func (t Tag) GoString() string
func (i Tag) String() string
type Type interface {
Common() *CommonType
String() string
Size() int64
}
A Type conventionally represents a pointer to any of the specific Type
structures (CharType, StructType, etc.).
type TypedefType struct {
CommonType
Type Type
}
A TypedefType represents a named type.
func (t *TypedefType) Size() int64
func (t *TypedefType) String() string
type UcharType struct {
BasicType
}
A UcharType represents an unsigned character type.
type UintType struct {
BasicType
}
A UintType represents an unsigned integer type.
type UnspecifiedType struct {
BasicType
}
An UnspecifiedType represents an implicit, unknown, ambiguous or nonexistent
type.
type UnsupportedType struct {
CommonType
Tag Tag
}
An UnsupportedType is a placeholder returned in situations where we
encounter a type that isn't supported.
func (t *UnsupportedType) String() string
type VoidType struct {
CommonType
}
A VoidType represents the C void type.
func (t *VoidType) String() string
type abbrev struct {
tag Tag
children bool
field []afield
}
a single entry's description: a sequence of attributes
type abbrevTable map[uint32]abbrev
a map from entry format ids to their descriptions
type afield struct {
attr Attr
fmt format
class Class
}
type buf struct {
dwarf *Data
order binary.ByteOrder
format dataFormat
name string
off Offset
data []byte
err error
}
Data buffer being decoded.
func makeBuf(d *Data, format dataFormat, name string, off Offset, data []byte) buf
func (b *buf) addr() uint64
Address-sized uint.
func (b *buf) bytes(n int) []byte
func (b *buf) entry(cu *Entry, atab abbrevTable, ubase Offset, vers int) *Entry
Entry reads a single entry from buf, decoding according to the given
abbreviation table.
func (b *buf) error(s string)
func (b *buf) int() int64
Signed int is a sign-extended varint.
func (b *buf) skip(n int)
func (b *buf) string() string
func (b *buf) uint() uint64
Unsigned int is just a varint.
func (b *buf) uint16() uint16
func (b *buf) uint24() uint32
func (b *buf) uint32() uint32
func (b *buf) uint64() uint64
func (b *buf) uint8() uint8
func (b *buf) unitLength() (length Offset, dwarf64 bool)
func (b *buf) varint() (c uint64, bits uint)
Read a varint, which is 7 bits per byte, little endian. the 0x80 bit means
read another byte.
type dataFormat interface {
version() int
dwarf64() (dwarf64 bool, isKnown bool)
addrsize() int
}
Data format, other than byte order. This affects the handling of certain
field formats.
type format uint32
A format is a DWARF data encoding format.
const (
formAddr format = 0x01
formDwarfBlock2 format = 0x03
formDwarfBlock4 format = 0x04
formData2 format = 0x05
formData4 format = 0x06
formData8 format = 0x07
formString format = 0x08
formDwarfBlock format = 0x09
formDwarfBlock1 format = 0x0A
formData1 format = 0x0B
formFlag format = 0x0C
formSdata format = 0x0D
formStrp format = 0x0E
formUdata format = 0x0F
formRefAddr format = 0x10
formRef1 format = 0x11
formRef2 format = 0x12
formRef4 format = 0x13
formRef8 format = 0x14
formRefUdata format = 0x15
formIndirect format = 0x16
formSecOffset format = 0x17
formExprloc format = 0x18
formFlagPresent format = 0x19
formRefSig8 format = 0x20
formStrx format = 0x1A
formAddrx format = 0x1B
formRefSup4 format = 0x1C
formStrpSup format = 0x1D
formData16 format = 0x1E
formLineStrp format = 0x1F
formImplicitConst format = 0x21
formLoclistx format = 0x22
formRnglistx format = 0x23
formRefSup8 format = 0x24
formStrx1 format = 0x25
formStrx2 format = 0x26
formStrx3 format = 0x27
formStrx4 format = 0x28
formAddrx1 format = 0x29
formAddrx2 format = 0x2A
formAddrx3 format = 0x2B
formAddrx4 format = 0x2C
formGnuRefAlt format = 0x1f20
formGnuStrpAlt format = 0x1f21
)
type lnctForm struct {
lnct int
form format
}
lnctForm is a pair of an LNCT code and a form. This represents an entry
in the directory name or file name description in the DWARF 5 line number
program header.
type typeFixer struct {
typedefs []*TypedefType
arraytypes []*Type
}
func (tf *typeFixer) apply()
func (tf *typeFixer) recordArrayType(t *Type)
type typeReader interface {
Seek(Offset)
Next() (*Entry, error)
clone() typeReader
offset() Offset
AddressSize() int
}
typeReader is used to read from either the info section or the types
section.
type typeUnit struct {
unit
}
The typeUnit format is a single type with a signature. It holds the same
data as a compilation unit.
func (u *typeUnit) addrsize() int
func (u *typeUnit) dwarf64() (bool, bool)
func (u *typeUnit) version() int
type typeUnitReader struct {
d *Data
tu *typeUnit
b buf
err error
}
typeUnitReader is a typeReader for a tagTypeUnit.
func (tur *typeUnitReader) AddressSize() int
AddressSize returns the size in bytes of addresses in the current type unit.
func (tur *typeUnitReader) Next() (*Entry, error)
Next reads the next Entry from the type unit.
func (tur *typeUnitReader) Seek(off Offset)
Seek to a new position in the type unit.
func (tur *typeUnitReader) clone() typeReader
clone returns a new reader for the type unit.
func (tur *typeUnitReader) offset() Offset
offset returns the current offset.
type unit struct {
data []byte
atable abbrevTable
asize int
vers int
}
func (u *unit) addrsize() int
func (u *unit) dwarf64() (bool, bool)
func (u *unit) version() int
type unknownFormat struct{}
Some parts of DWARF have no data format, e.g., abbrevs.
func (u unknownFormat) addrsize() int
func (u unknownFormat) dwarf64() (bool, bool)
func (u unknownFormat) version() int
debug/elf
func NewFile(r io.ReaderAt) (*File, error)
NewFile creates a new File for accessing an ELF binary in an underlying
reader. The ELF binary is expected to start at position 0 in the ReaderAt.
func Open(name string) (*File, error)
Open opens the named file using os.Open and prepares it for use as an ELF
binary.
func R_INFO(sym, typ uint32) uint64
func R_INFO32(sym, typ uint32) uint32
func R_SYM32(info uint32) uint32
func R_SYM64(info uint64) uint32
func R_TYPE32(info uint32) uint32
func R_TYPE64(info uint64) uint32
func ST_INFO(bind SymBind, typ SymType) uint8
func canApplyRelocation(sym *Symbol) bool
canApplyRelocation reports whether we should try to apply a relocation
to a DWARF data section, given a pointer to the symbol targeted by the
relocation. Most relocations in DWARF data tend to be section-relative,
but some target non-section symbols (for example, low_PC attrs on subprogram
or compilation unit DIEs that target function symbols).
func flagName(i uint32, names []intName, goSyntax bool) string
func getString(section []byte, start int) (string, bool)
getString extracts a string from an ELF string table.
func stringName(i uint32, names []intName, goSyntax bool) string
TYPES
type Chdr32 struct {
Type uint32
Size uint32
Addralign uint32
}
ELF32 Compression header.
type Chdr64 struct {
Type uint32
_ uint32 /* Reserved. */
Size uint64
Addralign uint64
}
ELF64 Compression header.
type Class byte
Class is found in Header.Ident[EI_CLASS] and Header.Class.
const (
ELFCLASSNONE Class = 0 /* Unknown class. */
ELFCLASS32 Class = 1 /* 32-bit architecture. */
ELFCLASS64 Class = 2 /* 64-bit architecture. */
)
func (i Class) GoString() string
func (i Class) String() string
type CompressionType int
Section compression type.
const (
COMPRESS_ZLIB CompressionType = 1 /* ZLIB compression. */
COMPRESS_ZSTD CompressionType = 2 /* ZSTD compression. */
COMPRESS_LOOS CompressionType = 0x60000000 /* First OS-specific. */
COMPRESS_HIOS CompressionType = 0x6fffffff /* Last OS-specific. */
COMPRESS_LOPROC CompressionType = 0x70000000 /* First processor-specific type. */
COMPRESS_HIPROC CompressionType = 0x7fffffff /* Last processor-specific type. */
)
func (i CompressionType) GoString() string
func (i CompressionType) String() string
type Data byte
Data is found in Header.Ident[EI_DATA] and Header.Data.
const (
ELFDATANONE Data = 0 /* Unknown data format. */
ELFDATA2LSB Data = 1 /* 2's complement little-endian. */
ELFDATA2MSB Data = 2 /* 2's complement big-endian. */
)
func (i Data) GoString() string
func (i Data) String() string
type Dyn32 struct {
Tag int32 /* Entry type. */
Val uint32 /* Integer/Address value. */
}
ELF32 Dynamic structure. The ".dynamic" section contains an array of them.
type Dyn64 struct {
Tag int64 /* Entry type. */
Val uint64 /* Integer/address value */
}
ELF64 Dynamic structure. The ".dynamic" section contains an array of them.
type DynFlag int
DT_FLAGS values.
const (
DF_ORIGIN DynFlag = 0x0001 /* Indicates that the object being loaded may
make reference to the
$ORIGIN substitution string */
DF_SYMBOLIC DynFlag = 0x0002 /* Indicates "symbolic" linking. */
DF_TEXTREL DynFlag = 0x0004 /* Indicates there may be relocations in non-writable segments. */
DF_BIND_NOW DynFlag = 0x0008 /* Indicates that the dynamic linker should
process all relocations for the object
containing this entry before transferring
control to the program. */
DF_STATIC_TLS DynFlag = 0x0010 /* Indicates that the shared object or
executable contains code using a static
thread-local storage scheme. */
)
func (i DynFlag) GoString() string
func (i DynFlag) String() string
type DynFlag1 uint32
DT_FLAGS_1 values.
const (
DF_1_NOW DynFlag1 = 0x00000001
DF_1_GLOBAL DynFlag1 = 0x00000002
DF_1_GROUP DynFlag1 = 0x00000004
DF_1_NODELETE DynFlag1 = 0x00000008
DF_1_LOADFLTR DynFlag1 = 0x00000010
DF_1_INITFIRST DynFlag1 = 0x00000020
DF_1_NOOPEN DynFlag1 = 0x00000040
DF_1_ORIGIN DynFlag1 = 0x00000080
DF_1_DIRECT DynFlag1 = 0x00000100
DF_1_TRANS DynFlag1 = 0x00000200
DF_1_INTERPOSE DynFlag1 = 0x00000400
DF_1_NODEFLIB DynFlag1 = 0x00000800
DF_1_NODUMP DynFlag1 = 0x00001000
DF_1_CONFALT DynFlag1 = 0x00002000
DF_1_ENDFILTEE DynFlag1 = 0x00004000
DF_1_DISPRELDNE DynFlag1 = 0x00008000
DF_1_DISPRELPND DynFlag1 = 0x00010000
DF_1_NODIRECT DynFlag1 = 0x00020000
DF_1_IGNMULDEF DynFlag1 = 0x00040000
DF_1_NOKSYMS DynFlag1 = 0x00080000
DF_1_NOHDR DynFlag1 = 0x00100000
DF_1_EDITED DynFlag1 = 0x00200000
DF_1_NORELOC DynFlag1 = 0x00400000
DF_1_SYMINTPOSE DynFlag1 = 0x00800000
DF_1_GLOBAUDIT DynFlag1 = 0x01000000
DF_1_SINGLETON DynFlag1 = 0x02000000
DF_1_STUB DynFlag1 = 0x04000000
DF_1_PIE DynFlag1 = 0x08000000
DF_1_KMOD DynFlag1 = 0x10000000
DF_1_WEAKFILTER DynFlag1 = 0x20000000
DF_1_NOCOMMON DynFlag1 = 0x40000000
)
func (i DynFlag1) GoString() string
func (i DynFlag1) String() string
type DynTag int
Dyn.Tag
const (
DT_NULL DynTag = 0 /* Terminating entry. */
DT_NEEDED DynTag = 1 /* String table offset of a needed shared library. */
DT_PLTRELSZ DynTag = 2 /* Total size in bytes of PLT relocations. */
DT_PLTGOT DynTag = 3 /* Processor-dependent address. */
DT_HASH DynTag = 4 /* Address of symbol hash table. */
DT_STRTAB DynTag = 5 /* Address of string table. */
DT_SYMTAB DynTag = 6 /* Address of symbol table. */
DT_RELA DynTag = 7 /* Address of ElfNN_Rela relocations. */
DT_RELASZ DynTag = 8 /* Total size of ElfNN_Rela relocations. */
DT_RELAENT DynTag = 9 /* Size of each ElfNN_Rela relocation entry. */
DT_STRSZ DynTag = 10 /* Size of string table. */
DT_SYMENT DynTag = 11 /* Size of each symbol table entry. */
DT_INIT DynTag = 12 /* Address of initialization function. */
DT_FINI DynTag = 13 /* Address of finalization function. */
DT_SONAME DynTag = 14 /* String table offset of shared object name. */
DT_RPATH DynTag = 15 /* String table offset of library path. [sup] */
DT_SYMBOLIC DynTag = 16 /* Indicates "symbolic" linking. [sup] */
DT_REL DynTag = 17 /* Address of ElfNN_Rel relocations. */
DT_RELSZ DynTag = 18 /* Total size of ElfNN_Rel relocations. */
DT_RELENT DynTag = 19 /* Size of each ElfNN_Rel relocation. */
DT_PLTREL DynTag = 20 /* Type of relocation used for PLT. */
DT_DEBUG DynTag = 21 /* Reserved (not used). */
DT_TEXTREL DynTag = 22 /* Indicates there may be relocations in non-writable segments. [sup] */
DT_JMPREL DynTag = 23 /* Address of PLT relocations. */
DT_BIND_NOW DynTag = 24 /* [sup] */
DT_INIT_ARRAY DynTag = 25 /* Address of the array of pointers to initialization functions */
DT_FINI_ARRAY DynTag = 26 /* Address of the array of pointers to termination functions */
DT_INIT_ARRAYSZ DynTag = 27 /* Size in bytes of the array of initialization functions. */
DT_FINI_ARRAYSZ DynTag = 28 /* Size in bytes of the array of termination functions. */
DT_RUNPATH DynTag = 29 /* String table offset of a null-terminated library search path string. */
DT_FLAGS DynTag = 30 /* Object specific flag values. */
DT_ENCODING DynTag = 32 /* Values greater than or equal to DT_ENCODING
and less than DT_LOOS follow the rules for
the interpretation of the d_un union
as follows: even == 'd_ptr', even == 'd_val'
or none */
DT_PREINIT_ARRAY DynTag = 32 /* Address of the array of pointers to pre-initialization functions. */
DT_PREINIT_ARRAYSZ DynTag = 33 /* Size in bytes of the array of pre-initialization functions. */
DT_SYMTAB_SHNDX DynTag = 34 /* Address of SHT_SYMTAB_SHNDX section. */
DT_LOOS DynTag = 0x6000000d /* First OS-specific */
DT_HIOS DynTag = 0x6ffff000 /* Last OS-specific */
DT_VALRNGLO DynTag = 0x6ffffd00
DT_GNU_PRELINKED DynTag = 0x6ffffdf5
DT_GNU_CONFLICTSZ DynTag = 0x6ffffdf6
DT_GNU_LIBLISTSZ DynTag = 0x6ffffdf7
DT_CHECKSUM DynTag = 0x6ffffdf8
DT_PLTPADSZ DynTag = 0x6ffffdf9
DT_MOVEENT DynTag = 0x6ffffdfa
DT_MOVESZ DynTag = 0x6ffffdfb
DT_FEATURE DynTag = 0x6ffffdfc
DT_POSFLAG_1 DynTag = 0x6ffffdfd
DT_SYMINSZ DynTag = 0x6ffffdfe
DT_SYMINENT DynTag = 0x6ffffdff
DT_VALRNGHI DynTag = 0x6ffffdff
DT_ADDRRNGLO DynTag = 0x6ffffe00
DT_GNU_HASH DynTag = 0x6ffffef5
DT_TLSDESC_PLT DynTag = 0x6ffffef6
DT_TLSDESC_GOT DynTag = 0x6ffffef7
DT_GNU_CONFLICT DynTag = 0x6ffffef8
DT_GNU_LIBLIST DynTag = 0x6ffffef9
DT_CONFIG DynTag = 0x6ffffefa
DT_DEPAUDIT DynTag = 0x6ffffefb
DT_AUDIT DynTag = 0x6ffffefc
DT_PLTPAD DynTag = 0x6ffffefd
DT_MOVETAB DynTag = 0x6ffffefe
DT_SYMINFO DynTag = 0x6ffffeff
DT_ADDRRNGHI DynTag = 0x6ffffeff
DT_VERSYM DynTag = 0x6ffffff0
DT_RELACOUNT DynTag = 0x6ffffff9
DT_RELCOUNT DynTag = 0x6ffffffa
DT_FLAGS_1 DynTag = 0x6ffffffb
DT_VERDEF DynTag = 0x6ffffffc
DT_VERDEFNUM DynTag = 0x6ffffffd
DT_VERNEED DynTag = 0x6ffffffe
DT_VERNEEDNUM DynTag = 0x6fffffff
DT_LOPROC DynTag = 0x70000000 /* First processor-specific type. */
DT_MIPS_RLD_VERSION DynTag = 0x70000001
DT_MIPS_TIME_STAMP DynTag = 0x70000002
DT_MIPS_ICHECKSUM DynTag = 0x70000003
DT_MIPS_IVERSION DynTag = 0x70000004
DT_MIPS_FLAGS DynTag = 0x70000005
DT_MIPS_BASE_ADDRESS DynTag = 0x70000006
DT_MIPS_MSYM DynTag = 0x70000007
DT_MIPS_CONFLICT DynTag = 0x70000008
DT_MIPS_LIBLIST DynTag = 0x70000009
DT_MIPS_LOCAL_GOTNO DynTag = 0x7000000a
DT_MIPS_CONFLICTNO DynTag = 0x7000000b
DT_MIPS_LIBLISTNO DynTag = 0x70000010
DT_MIPS_SYMTABNO DynTag = 0x70000011
DT_MIPS_UNREFEXTNO DynTag = 0x70000012
DT_MIPS_GOTSYM DynTag = 0x70000013
DT_MIPS_HIPAGENO DynTag = 0x70000014
DT_MIPS_RLD_MAP DynTag = 0x70000016
DT_MIPS_DELTA_CLASS DynTag = 0x70000017
DT_MIPS_DELTA_CLASS_NO DynTag = 0x70000018
DT_MIPS_DELTA_INSTANCE DynTag = 0x70000019
DT_MIPS_DELTA_INSTANCE_NO DynTag = 0x7000001a
DT_MIPS_DELTA_RELOC DynTag = 0x7000001b
DT_MIPS_DELTA_RELOC_NO DynTag = 0x7000001c
DT_MIPS_DELTA_SYM DynTag = 0x7000001d
DT_MIPS_DELTA_SYM_NO DynTag = 0x7000001e
DT_MIPS_DELTA_CLASSSYM DynTag = 0x70000020
DT_MIPS_DELTA_CLASSSYM_NO DynTag = 0x70000021
DT_MIPS_CXX_FLAGS DynTag = 0x70000022
DT_MIPS_PIXIE_INIT DynTag = 0x70000023
DT_MIPS_SYMBOL_LIB DynTag = 0x70000024
DT_MIPS_LOCALPAGE_GOTIDX DynTag = 0x70000025
DT_MIPS_LOCAL_GOTIDX DynTag = 0x70000026
DT_MIPS_HIDDEN_GOTIDX DynTag = 0x70000027
DT_MIPS_PROTECTED_GOTIDX DynTag = 0x70000028
DT_MIPS_OPTIONS DynTag = 0x70000029
DT_MIPS_INTERFACE DynTag = 0x7000002a
DT_MIPS_DYNSTR_ALIGN DynTag = 0x7000002b
DT_MIPS_INTERFACE_SIZE DynTag = 0x7000002c
DT_MIPS_RLD_TEXT_RESOLVE_ADDR DynTag = 0x7000002d
DT_MIPS_PERF_SUFFIX DynTag = 0x7000002e
DT_MIPS_COMPACT_SIZE DynTag = 0x7000002f
DT_MIPS_GP_VALUE DynTag = 0x70000030
DT_MIPS_AUX_DYNAMIC DynTag = 0x70000031
DT_MIPS_PLTGOT DynTag = 0x70000032
DT_MIPS_RWPLT DynTag = 0x70000034
DT_MIPS_RLD_MAP_REL DynTag = 0x70000035
DT_PPC_GOT DynTag = 0x70000000
DT_PPC_OPT DynTag = 0x70000001
DT_PPC64_GLINK DynTag = 0x70000000
DT_PPC64_OPD DynTag = 0x70000001
DT_PPC64_OPDSZ DynTag = 0x70000002
DT_PPC64_OPT DynTag = 0x70000003
DT_SPARC_REGISTER DynTag = 0x70000001
DT_AUXILIARY DynTag = 0x7ffffffd
DT_USED DynTag = 0x7ffffffe
DT_FILTER DynTag = 0x7fffffff
DT_HIPROC DynTag = 0x7fffffff /* Last processor-specific type. */
)
func (i DynTag) GoString() string
func (i DynTag) String() string
type DynamicVersion struct {
Flags DynamicVersionFlag
}
DynamicVersion is a version defined by a dynamic object. This describes
entries in the ELF SHT_GNU_verdef section. We assume that the vd_version
field is 1. Note that the name of the version appears here; it is not in the
first Deps entry as it is in the ELF file.
type DynamicVersionDep struct {
Flags DynamicVersionFlag
}
DynamicVersionDep is a version needed from some shared library.
type DynamicVersionFlag uint16
Dynamic version flags.
const (
VER_FLG_BASE DynamicVersionFlag = 0x1 /* Version definition of the file. */
VER_FLG_WEAK DynamicVersionFlag = 0x2 /* Weak version identifier. */
VER_FLG_INFO DynamicVersionFlag = 0x4 /* Reference exists for informational purposes. */
)
type DynamicVersionNeed struct {
}
DynamicVersionNeed describes a shared library needed by a dynamic object,
with a list of the versions needed from that shared library. This describes
entries in the ELF SHT_GNU_verneed section. We assume that the vn_version
field is 1.
type File struct {
FileHeader
Sections []*Section
Progs []*Prog
closer io.Closer
dynVers []DynamicVersion
dynVerNeeds []DynamicVersionNeed
gnuVersym []byte
}
A File represents an open ELF file.
func (f *File) Close() error
Close closes the File. If the File was created using NewFile directly
instead of Open, Close has no effect.
func (f *File) DWARF() (*dwarf.Data, error)
func (f *File) DynString(tag DynTag) ([]string, error)
DynString returns the strings listed for the given tag in the file's dynamic
section.
The tag must be one that takes string values: DT_NEEDED, DT_SONAME,
DT_RPATH, or DT_RUNPATH.
func (f *File) DynValue(tag DynTag) ([]uint64, error)
DynValue returns the values listed for the given tag in the file's dynamic
section.
func (f *File) DynamicSymbols() ([]Symbol, error)
DynamicSymbols returns the dynamic symbol table for f. The symbols will be
listed in the order they appear in f.
If f has a symbol version table, the returned File.Symbols will have
initialized Version and Library fields.
For compatibility with File.Symbols, File.DynamicSymbols omits the null
symbol at index 0. After retrieving the symbols as symtab, an externally
supplied index x corresponds to symtab[x-1], not symtab[x].
func (f *File) DynamicVersionNeeds() ([]DynamicVersionNeed, error)
DynamicVersionNeeds returns version dependencies for a dynamic object.
func (f *File) DynamicVersions() ([]DynamicVersion, error)
DynamicVersions returns version information for a dynamic object.
func (f *File) ImportedLibraries() ([]string, error)
ImportedLibraries returns the names of all libraries referred to by the
binary f that are expected to be linked with the binary at dynamic link
time.
func (f *File) ImportedSymbols() ([]ImportedSymbol, error)
ImportedSymbols returns the names of all symbols referred to by the binary
f that are expected to be satisfied by other libraries at dynamic load time.
It does not return weak symbols.
func (f *File) Section(name string) *Section
Section returns a section with the given name, or nil if no such section
exists.
func (f *File) SectionByType(typ SectionType) *Section
SectionByType returns the first section in f with the given type, or nil if
there is no such section.
func (f *File) Symbols() ([]Symbol, error)
Symbols returns the symbol table for f. The symbols will be listed in the
order they appear in f.
For compatibility with Go 1.0, Symbols omits the null symbol at index 0.
After retrieving the symbols as symtab, an externally supplied index x
corresponds to symtab[x-1], not symtab[x].
func (f *File) applyRelocations(dst []byte, rels []byte) error
applyRelocations applies relocations to dst. rels is a relocations section
in REL or RELA format.
func (f *File) applyRelocations386(dst []byte, rels []byte) error
func (f *File) applyRelocationsAMD64(dst []byte, rels []byte) error
func (f *File) applyRelocationsARM(dst []byte, rels []byte) error
func (f *File) applyRelocationsARM64(dst []byte, rels []byte) error
func (f *File) applyRelocationsLOONG64(dst []byte, rels []byte) error
func (f *File) applyRelocationsMIPS(dst []byte, rels []byte) error
func (f *File) applyRelocationsMIPS64(dst []byte, rels []byte) error
func (f *File) applyRelocationsPPC(dst []byte, rels []byte) error
func (f *File) applyRelocationsPPC64(dst []byte, rels []byte) error
func (f *File) applyRelocationsRISCV64(dst []byte, rels []byte) error
func (f *File) applyRelocationsSPARC64(dst []byte, rels []byte) error
func (f *File) applyRelocationss390x(dst []byte, rels []byte) error
func (f *File) dynamicVersionNeeds(str []byte) error
dynamicVersionNeeds returns version dependencies for a dynamic object.
func (f *File) dynamicVersions(str []byte) error
dynamicVersions returns version information for a dynamic object.
func (f *File) getSymbols(typ SectionType) ([]Symbol, []byte, error)
getSymbols returns a slice of Symbols from parsing the symbol table with the
given type, along with the associated string table.
func (f *File) getSymbols32(typ SectionType) ([]Symbol, []byte, error)
func (f *File) getSymbols64(typ SectionType) ([]Symbol, []byte, error)
func (f *File) gnuVersion(i int) (versionIndex int16, version string, library string, versionFlags SymbolVersionScope)
gnuVersion adds Library and Version information to sym, which came from
offset i of the symbol table.
func (f *File) gnuVersionInit(str []byte) (bool, error)
gnuVersionInit parses the GNU version tables for use by calls to gnuVersion.
It reports whether any version tables were found.
func (f *File) stringTable(link uint32) ([]byte, error)
stringTable reads and returns the string table given by the specified link
value.
type FileHeader struct {
Class Class
Data Data
Version Version
OSABI OSABI
ABIVersion uint8
ByteOrder binary.ByteOrder
Type Type
Machine Machine
Entry uint64
}
A FileHeader represents an ELF file header.
type FormatError struct {
off int64
msg string
val any
}
func (e *FormatError) Error() string
type Header32 struct {
Ident [EI_NIDENT]byte /* File identification. */
Type uint16 /* File type. */
Machine uint16 /* Machine architecture. */
Version uint32 /* ELF format version. */
Entry uint32 /* Entry point. */
Phoff uint32 /* Program header file offset. */
Shoff uint32 /* Section header file offset. */
Flags uint32 /* Architecture-specific flags. */
Ehsize uint16 /* Size of ELF header in bytes. */
Phentsize uint16 /* Size of program header entry. */
Phnum uint16 /* Number of program header entries. */
Shentsize uint16 /* Size of section header entry. */
Shnum uint16 /* Number of section header entries. */
Shstrndx uint16 /* Section name strings section. */
}
ELF32 File header.
type Header64 struct {
Ident [EI_NIDENT]byte /* File identification. */
Type uint16 /* File type. */
Machine uint16 /* Machine architecture. */
Version uint32 /* ELF format version. */
Entry uint64 /* Entry point. */
Phoff uint64 /* Program header file offset. */
Shoff uint64 /* Section header file offset. */
Flags uint32 /* Architecture-specific flags. */
Ehsize uint16 /* Size of ELF header in bytes. */
Phentsize uint16 /* Size of program header entry. */
Phnum uint16 /* Number of program header entries. */
Shentsize uint16 /* Size of section header entry. */
Shnum uint16 /* Number of section header entries. */
Shstrndx uint16 /* Section name strings section. */
}
ELF64 file header.
type ImportedSymbol struct {
Name string
Version string
Library string
}
type Machine uint16
Machine is found in Header.Machine.
const (
EM_NONE Machine = 0 /* Unknown machine. */
EM_M32 Machine = 1 /* AT&T WE32100. */
EM_SPARC Machine = 2 /* Sun SPARC. */
EM_386 Machine = 3 /* Intel i386. */
EM_68K Machine = 4 /* Motorola 68000. */
EM_88K Machine = 5 /* Motorola 88000. */
EM_860 Machine = 7 /* Intel i860. */
EM_MIPS Machine = 8 /* MIPS R3000 Big-Endian only. */
EM_S370 Machine = 9 /* IBM System/370. */
EM_MIPS_RS3_LE Machine = 10 /* MIPS R3000 Little-Endian. */
EM_PARISC Machine = 15 /* HP PA-RISC. */
EM_VPP500 Machine = 17 /* Fujitsu VPP500. */
EM_SPARC32PLUS Machine = 18 /* SPARC v8plus. */
EM_960 Machine = 19 /* Intel 80960. */
EM_PPC Machine = 20 /* PowerPC 32-bit. */
EM_PPC64 Machine = 21 /* PowerPC 64-bit. */
EM_S390 Machine = 22 /* IBM System/390. */
EM_V800 Machine = 36 /* NEC V800. */
EM_FR20 Machine = 37 /* Fujitsu FR20. */
EM_RH32 Machine = 38 /* TRW RH-32. */
EM_RCE Machine = 39 /* Motorola RCE. */
EM_ARM Machine = 40 /* ARM. */
EM_SH Machine = 42 /* Hitachi SH. */
EM_SPARCV9 Machine = 43 /* SPARC v9 64-bit. */
EM_TRICORE Machine = 44 /* Siemens TriCore embedded processor. */
EM_ARC Machine = 45 /* Argonaut RISC Core. */
EM_H8_300 Machine = 46 /* Hitachi H8/300. */
EM_H8_300H Machine = 47 /* Hitachi H8/300H. */
EM_H8S Machine = 48 /* Hitachi H8S. */
EM_H8_500 Machine = 49 /* Hitachi H8/500. */
EM_IA_64 Machine = 50 /* Intel IA-64 Processor. */
EM_MIPS_X Machine = 51 /* Stanford MIPS-X. */
EM_COLDFIRE Machine = 52 /* Motorola ColdFire. */
EM_68HC12 Machine = 53 /* Motorola M68HC12. */
EM_MMA Machine = 54 /* Fujitsu MMA. */
EM_PCP Machine = 55 /* Siemens PCP. */
EM_NCPU Machine = 56 /* Sony nCPU. */
EM_NDR1 Machine = 57 /* Denso NDR1 microprocessor. */
EM_STARCORE Machine = 58 /* Motorola Star*Core processor. */
EM_ME16 Machine = 59 /* Toyota ME16 processor. */
EM_ST100 Machine = 60 /* STMicroelectronics ST100 processor. */
EM_TINYJ Machine = 61 /* Advanced Logic Corp. TinyJ processor. */
EM_X86_64 Machine = 62 /* Advanced Micro Devices x86-64 */
EM_PDSP Machine = 63 /* Sony DSP Processor */
EM_PDP10 Machine = 64 /* Digital Equipment Corp. PDP-10 */
EM_PDP11 Machine = 65 /* Digital Equipment Corp. PDP-11 */
EM_FX66 Machine = 66 /* Siemens FX66 microcontroller */
EM_ST9PLUS Machine = 67 /* STMicroelectronics ST9+ 8/16 bit microcontroller */
EM_ST7 Machine = 68 /* STMicroelectronics ST7 8-bit microcontroller */
EM_68HC16 Machine = 69 /* Motorola MC68HC16 Microcontroller */
EM_68HC11 Machine = 70 /* Motorola MC68HC11 Microcontroller */
EM_68HC08 Machine = 71 /* Motorola MC68HC08 Microcontroller */
EM_68HC05 Machine = 72 /* Motorola MC68HC05 Microcontroller */
EM_SVX Machine = 73 /* Silicon Graphics SVx */
EM_ST19 Machine = 74 /* STMicroelectronics ST19 8-bit microcontroller */
EM_VAX Machine = 75 /* Digital VAX */
EM_CRIS Machine = 76 /* Axis Communications 32-bit embedded processor */
EM_JAVELIN Machine = 77 /* Infineon Technologies 32-bit embedded processor */
EM_FIREPATH Machine = 78 /* Element 14 64-bit DSP Processor */
EM_ZSP Machine = 79 /* LSI Logic 16-bit DSP Processor */
EM_MMIX Machine = 80 /* Donald Knuth's educational 64-bit processor */
EM_HUANY Machine = 81 /* Harvard University machine-independent object files */
EM_PRISM Machine = 82 /* SiTera Prism */
EM_AVR Machine = 83 /* Atmel AVR 8-bit microcontroller */
EM_FR30 Machine = 84 /* Fujitsu FR30 */
EM_D10V Machine = 85 /* Mitsubishi D10V */
EM_D30V Machine = 86 /* Mitsubishi D30V */
EM_V850 Machine = 87 /* NEC v850 */
EM_M32R Machine = 88 /* Mitsubishi M32R */
EM_MN10300 Machine = 89 /* Matsushita MN10300 */
EM_MN10200 Machine = 90 /* Matsushita MN10200 */
EM_PJ Machine = 91 /* picoJava */
EM_OPENRISC Machine = 92 /* OpenRISC 32-bit embedded processor */
EM_ARC_COMPACT Machine = 93 /* ARC International ARCompact processor (old spelling/synonym: EM_ARC_A5) */
EM_XTENSA Machine = 94 /* Tensilica Xtensa Architecture */
EM_VIDEOCORE Machine = 95 /* Alphamosaic VideoCore processor */
EM_TMM_GPP Machine = 96 /* Thompson Multimedia General Purpose Processor */
EM_NS32K Machine = 97 /* National Semiconductor 32000 series */
EM_TPC Machine = 98 /* Tenor Network TPC processor */
EM_SNP1K Machine = 99 /* Trebia SNP 1000 processor */
EM_ST200 Machine = 100 /* STMicroelectronics (www.st.com) ST200 microcontroller */
EM_IP2K Machine = 101 /* Ubicom IP2xxx microcontroller family */
EM_MAX Machine = 102 /* MAX Processor */
EM_CR Machine = 103 /* National Semiconductor CompactRISC microprocessor */
EM_F2MC16 Machine = 104 /* Fujitsu F2MC16 */
EM_MSP430 Machine = 105 /* Texas Instruments embedded microcontroller msp430 */
EM_BLACKFIN Machine = 106 /* Analog Devices Blackfin (DSP) processor */
EM_SE_C33 Machine = 107 /* S1C33 Family of Seiko Epson processors */
EM_SEP Machine = 108 /* Sharp embedded microprocessor */
EM_ARCA Machine = 109 /* Arca RISC Microprocessor */
EM_UNICORE Machine = 110 /* Microprocessor series from PKU-Unity Ltd. and MPRC of Peking University */
EM_EXCESS Machine = 111 /* eXcess: 16/32/64-bit configurable embedded CPU */
EM_DXP Machine = 112 /* Icera Semiconductor Inc. Deep Execution Processor */
EM_ALTERA_NIOS2 Machine = 113 /* Altera Nios II soft-core processor */
EM_CRX Machine = 114 /* National Semiconductor CompactRISC CRX microprocessor */
EM_XGATE Machine = 115 /* Motorola XGATE embedded processor */
EM_C166 Machine = 116 /* Infineon C16x/XC16x processor */
EM_M16C Machine = 117 /* Renesas M16C series microprocessors */
EM_DSPIC30F Machine = 118 /* Microchip Technology dsPIC30F Digital Signal Controller */
EM_CE Machine = 119 /* Freescale Communication Engine RISC core */
EM_M32C Machine = 120 /* Renesas M32C series microprocessors */
EM_TSK3000 Machine = 131 /* Altium TSK3000 core */
EM_RS08 Machine = 132 /* Freescale RS08 embedded processor */
EM_SHARC Machine = 133 /* Analog Devices SHARC family of 32-bit DSP processors */
EM_ECOG2 Machine = 134 /* Cyan Technology eCOG2 microprocessor */
EM_SCORE7 Machine = 135 /* Sunplus S+core7 RISC processor */
EM_DSP24 Machine = 136 /* New Japan Radio (NJR) 24-bit DSP Processor */
EM_VIDEOCORE3 Machine = 137 /* Broadcom VideoCore III processor */
EM_LATTICEMICO32 Machine = 138 /* RISC processor for Lattice FPGA architecture */
EM_SE_C17 Machine = 139 /* Seiko Epson C17 family */
EM_TI_C6000 Machine = 140 /* The Texas Instruments TMS320C6000 DSP family */
EM_TI_C2000 Machine = 141 /* The Texas Instruments TMS320C2000 DSP family */
EM_TI_C5500 Machine = 142 /* The Texas Instruments TMS320C55x DSP family */
EM_TI_ARP32 Machine = 143 /* Texas Instruments Application Specific RISC Processor, 32bit fetch */
EM_TI_PRU Machine = 144 /* Texas Instruments Programmable Realtime Unit */
EM_MMDSP_PLUS Machine = 160 /* STMicroelectronics 64bit VLIW Data Signal Processor */
EM_CYPRESS_M8C Machine = 161 /* Cypress M8C microprocessor */
EM_R32C Machine = 162 /* Renesas R32C series microprocessors */
EM_TRIMEDIA Machine = 163 /* NXP Semiconductors TriMedia architecture family */
EM_QDSP6 Machine = 164 /* QUALCOMM DSP6 Processor */
EM_8051 Machine = 165 /* Intel 8051 and variants */
EM_STXP7X Machine = 166 /* STMicroelectronics STxP7x family of configurable and extensible RISC processors */
EM_NDS32 Machine = 167 /* Andes Technology compact code size embedded RISC processor family */
EM_ECOG1 Machine = 168 /* Cyan Technology eCOG1X family */
EM_ECOG1X Machine = 168 /* Cyan Technology eCOG1X family */
EM_MAXQ30 Machine = 169 /* Dallas Semiconductor MAXQ30 Core Micro-controllers */
EM_XIMO16 Machine = 170 /* New Japan Radio (NJR) 16-bit DSP Processor */
EM_MANIK Machine = 171 /* M2000 Reconfigurable RISC Microprocessor */
EM_CRAYNV2 Machine = 172 /* Cray Inc. NV2 vector architecture */
EM_RX Machine = 173 /* Renesas RX family */
EM_METAG Machine = 174 /* Imagination Technologies META processor architecture */
EM_MCST_ELBRUS Machine = 175 /* MCST Elbrus general purpose hardware architecture */
EM_ECOG16 Machine = 176 /* Cyan Technology eCOG16 family */
EM_CR16 Machine = 177 /* National Semiconductor CompactRISC CR16 16-bit microprocessor */
EM_ETPU Machine = 178 /* Freescale Extended Time Processing Unit */
EM_SLE9X Machine = 179 /* Infineon Technologies SLE9X core */
EM_L10M Machine = 180 /* Intel L10M */
EM_K10M Machine = 181 /* Intel K10M */
EM_AARCH64 Machine = 183 /* ARM 64-bit Architecture (AArch64) */
EM_AVR32 Machine = 185 /* Atmel Corporation 32-bit microprocessor family */
EM_STM8 Machine = 186 /* STMicroeletronics STM8 8-bit microcontroller */
EM_TILE64 Machine = 187 /* Tilera TILE64 multicore architecture family */
EM_TILEPRO Machine = 188 /* Tilera TILEPro multicore architecture family */
EM_MICROBLAZE Machine = 189 /* Xilinx MicroBlaze 32-bit RISC soft processor core */
EM_CUDA Machine = 190 /* NVIDIA CUDA architecture */
EM_TILEGX Machine = 191 /* Tilera TILE-Gx multicore architecture family */
EM_CLOUDSHIELD Machine = 192 /* CloudShield architecture family */
EM_COREA_1ST Machine = 193 /* KIPO-KAIST Core-A 1st generation processor family */
EM_COREA_2ND Machine = 194 /* KIPO-KAIST Core-A 2nd generation processor family */
EM_ARC_COMPACT2 Machine = 195 /* Synopsys ARCompact V2 */
EM_OPEN8 Machine = 196 /* Open8 8-bit RISC soft processor core */
EM_RL78 Machine = 197 /* Renesas RL78 family */
EM_VIDEOCORE5 Machine = 198 /* Broadcom VideoCore V processor */
EM_78KOR Machine = 199 /* Renesas 78KOR family */
EM_56800EX Machine = 200 /* Freescale 56800EX Digital Signal Controller (DSC) */
EM_BA1 Machine = 201 /* Beyond BA1 CPU architecture */
EM_BA2 Machine = 202 /* Beyond BA2 CPU architecture */
EM_XCORE Machine = 203 /* XMOS xCORE processor family */
EM_MCHP_PIC Machine = 204 /* Microchip 8-bit PIC(r) family */
EM_INTEL205 Machine = 205 /* Reserved by Intel */
EM_INTEL206 Machine = 206 /* Reserved by Intel */
EM_INTEL207 Machine = 207 /* Reserved by Intel */
EM_INTEL208 Machine = 208 /* Reserved by Intel */
EM_INTEL209 Machine = 209 /* Reserved by Intel */
EM_KM32 Machine = 210 /* KM211 KM32 32-bit processor */
EM_KMX32 Machine = 211 /* KM211 KMX32 32-bit processor */
EM_KMX16 Machine = 212 /* KM211 KMX16 16-bit processor */
EM_KMX8 Machine = 213 /* KM211 KMX8 8-bit processor */
EM_KVARC Machine = 214 /* KM211 KVARC processor */
EM_CDP Machine = 215 /* Paneve CDP architecture family */
EM_COGE Machine = 216 /* Cognitive Smart Memory Processor */
EM_COOL Machine = 217 /* Bluechip Systems CoolEngine */
EM_NORC Machine = 218 /* Nanoradio Optimized RISC */
EM_CSR_KALIMBA Machine = 219 /* CSR Kalimba architecture family */
EM_Z80 Machine = 220 /* Zilog Z80 */
EM_VISIUM Machine = 221 /* Controls and Data Services VISIUMcore processor */
EM_FT32 Machine = 222 /* FTDI Chip FT32 high performance 32-bit RISC architecture */
EM_MOXIE Machine = 223 /* Moxie processor family */
EM_AMDGPU Machine = 224 /* AMD GPU architecture */
EM_RISCV Machine = 243 /* RISC-V */
EM_LANAI Machine = 244 /* Lanai 32-bit processor */
EM_BPF Machine = 247 /* Linux BPF – in-kernel virtual machine */
EM_LOONGARCH Machine = 258 /* LoongArch */
/* Non-standard or deprecated. */
EM_486 Machine = 6 /* Intel i486. */
EM_MIPS_RS4_BE Machine = 10 /* MIPS R4000 Big-Endian */
EM_ALPHA_STD Machine = 41 /* Digital Alpha (standard value). */
EM_ALPHA Machine = 0x9026 /* Alpha (written in the absence of an ABI) */
)
func (i Machine) GoString() string
func (i Machine) String() string
type NType int
NType values; used in core files.
const (
NT_PRSTATUS NType = 1 /* Process status. */
NT_FPREGSET NType = 2 /* Floating point registers. */
NT_PRPSINFO NType = 3 /* Process state info. */
)
func (i NType) GoString() string
func (i NType) String() string
type OSABI byte
OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI.
const (
ELFOSABI_NONE OSABI = 0 /* UNIX System V ABI */
ELFOSABI_HPUX OSABI = 1 /* HP-UX operating system */
ELFOSABI_NETBSD OSABI = 2 /* NetBSD */
ELFOSABI_LINUX OSABI = 3 /* Linux */
ELFOSABI_HURD OSABI = 4 /* Hurd */
ELFOSABI_86OPEN OSABI = 5 /* 86Open common IA32 ABI */
ELFOSABI_SOLARIS OSABI = 6 /* Solaris */
ELFOSABI_AIX OSABI = 7 /* AIX */
ELFOSABI_IRIX OSABI = 8 /* IRIX */
ELFOSABI_FREEBSD OSABI = 9 /* FreeBSD */
ELFOSABI_TRU64 OSABI = 10 /* TRU64 UNIX */
ELFOSABI_MODESTO OSABI = 11 /* Novell Modesto */
ELFOSABI_OPENBSD OSABI = 12 /* OpenBSD */
ELFOSABI_OPENVMS OSABI = 13 /* Open VMS */
ELFOSABI_NSK OSABI = 14 /* HP Non-Stop Kernel */
ELFOSABI_AROS OSABI = 15 /* Amiga Research OS */
ELFOSABI_FENIXOS OSABI = 16 /* The FenixOS highly scalable multi-core OS */
ELFOSABI_CLOUDABI OSABI = 17 /* Nuxi CloudABI */
ELFOSABI_ARM OSABI = 97 /* ARM */
ELFOSABI_STANDALONE OSABI = 255 /* Standalone (embedded) application */
)
func (i OSABI) GoString() string
func (i OSABI) String() string
type Prog struct {
ProgHeader
io.ReaderAt
sr *io.SectionReader
}
A Prog represents a single ELF program header in an ELF binary.
func (p *Prog) Open() io.ReadSeeker
Open returns a new ReadSeeker reading the ELF program body.
type Prog32 struct {
Type uint32 /* Entry type. */
Off uint32 /* File offset of contents. */
Vaddr uint32 /* Virtual address in memory image. */
Paddr uint32 /* Physical address (not used). */
Filesz uint32 /* Size of contents in file. */
Memsz uint32 /* Size of contents in memory. */
Flags uint32 /* Access permission flags. */
Align uint32 /* Alignment in memory and file. */
}
ELF32 Program header.
type Prog64 struct {
Type uint32 /* Entry type. */
Flags uint32 /* Access permission flags. */
Off uint64 /* File offset of contents. */
Vaddr uint64 /* Virtual address in memory image. */
Paddr uint64 /* Physical address (not used). */
Filesz uint64 /* Size of contents in file. */
Memsz uint64 /* Size of contents in memory. */
Align uint64 /* Alignment in memory and file. */
}
ELF64 Program header.
type ProgFlag uint32
Prog.Flag
const (
PF_X ProgFlag = 0x1 /* Executable. */
PF_W ProgFlag = 0x2 /* Writable. */
PF_R ProgFlag = 0x4 /* Readable. */
PF_MASKOS ProgFlag = 0x0ff00000 /* Operating system-specific. */
PF_MASKPROC ProgFlag = 0xf0000000 /* Processor-specific. */
)
func (i ProgFlag) GoString() string
func (i ProgFlag) String() string
type ProgHeader struct {
Type ProgType
Flags ProgFlag
Off uint64
Vaddr uint64
Paddr uint64
Filesz uint64
Memsz uint64
Align uint64
}
A ProgHeader represents a single ELF program header.
type ProgType int
Prog.Type
const (
PT_NULL ProgType = 0 /* Unused entry. */
PT_LOAD ProgType = 1 /* Loadable segment. */
PT_DYNAMIC ProgType = 2 /* Dynamic linking information segment. */
PT_INTERP ProgType = 3 /* Pathname of interpreter. */
PT_NOTE ProgType = 4 /* Auxiliary information. */
PT_SHLIB ProgType = 5 /* Reserved (not used). */
PT_PHDR ProgType = 6 /* Location of program header itself. */
PT_TLS ProgType = 7 /* Thread local storage segment */
PT_LOOS ProgType = 0x60000000 /* First OS-specific. */
PT_GNU_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
PT_GNU_STACK ProgType = 0x6474e551 /* Stack flags */
PT_GNU_RELRO ProgType = 0x6474e552 /* Read only after relocs */
PT_GNU_PROPERTY ProgType = 0x6474e553 /* GNU property */
PT_GNU_MBIND_LO ProgType = 0x6474e555 /* Mbind segments start */
PT_GNU_MBIND_HI ProgType = 0x6474f554 /* Mbind segments finish */
PT_PAX_FLAGS ProgType = 0x65041580 /* PAX flags */
PT_OPENBSD_RANDOMIZE ProgType = 0x65a3dbe6 /* Random data */
PT_OPENBSD_WXNEEDED ProgType = 0x65a3dbe7 /* W^X violations */
PT_OPENBSD_NOBTCFI ProgType = 0x65a3dbe8 /* No branch target CFI */
PT_OPENBSD_BOOTDATA ProgType = 0x65a41be6 /* Boot arguments */
PT_SUNW_EH_FRAME ProgType = 0x6474e550 /* Frame unwind information */
PT_SUNWSTACK ProgType = 0x6ffffffb /* Stack segment */
PT_HIOS ProgType = 0x6fffffff /* Last OS-specific. */
PT_LOPROC ProgType = 0x70000000 /* First processor-specific type. */
PT_ARM_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
PT_ARM_EXIDX ProgType = 0x70000001 /* Exception unwind tables */
PT_AARCH64_ARCHEXT ProgType = 0x70000000 /* Architecture compatibility */
PT_AARCH64_UNWIND ProgType = 0x70000001 /* Exception unwind tables */
PT_MIPS_REGINFO ProgType = 0x70000000 /* Register usage */
PT_MIPS_RTPROC ProgType = 0x70000001 /* Runtime procedures */
PT_MIPS_OPTIONS ProgType = 0x70000002 /* Options */
PT_MIPS_ABIFLAGS ProgType = 0x70000003 /* ABI flags */
PT_S390_PGSTE ProgType = 0x70000000 /* 4k page table size */
PT_HIPROC ProgType = 0x7fffffff /* Last processor-specific type. */
)
func (i ProgType) GoString() string
func (i ProgType) String() string
type R_386 int
Relocation types for 386.
const (
R_386_NONE R_386 = 0 /* No relocation. */
R_386_32 R_386 = 1 /* Add symbol value. */
R_386_PC32 R_386 = 2 /* Add PC-relative symbol value. */
R_386_GOT32 R_386 = 3 /* Add PC-relative GOT offset. */
R_386_PLT32 R_386 = 4 /* Add PC-relative PLT offset. */
R_386_COPY R_386 = 5 /* Copy data from shared object. */
R_386_GLOB_DAT R_386 = 6 /* Set GOT entry to data address. */
R_386_JMP_SLOT R_386 = 7 /* Set GOT entry to code address. */
R_386_RELATIVE R_386 = 8 /* Add load address of shared object. */
R_386_GOTOFF R_386 = 9 /* Add GOT-relative symbol address. */
R_386_GOTPC R_386 = 10 /* Add PC-relative GOT table address. */
R_386_32PLT R_386 = 11
R_386_TLS_TPOFF R_386 = 14 /* Negative offset in static TLS block */
R_386_TLS_IE R_386 = 15 /* Absolute address of GOT for -ve static TLS */
R_386_TLS_GOTIE R_386 = 16 /* GOT entry for negative static TLS block */
R_386_TLS_LE R_386 = 17 /* Negative offset relative to static TLS */
R_386_TLS_GD R_386 = 18 /* 32 bit offset to GOT (index,off) pair */
R_386_TLS_LDM R_386 = 19 /* 32 bit offset to GOT (index,zero) pair */
R_386_16 R_386 = 20
R_386_PC16 R_386 = 21
R_386_8 R_386 = 22
R_386_PC8 R_386 = 23
R_386_TLS_GD_32 R_386 = 24 /* 32 bit offset to GOT (index,off) pair */
R_386_TLS_GD_PUSH R_386 = 25 /* pushl instruction for Sun ABI GD sequence */
R_386_TLS_GD_CALL R_386 = 26 /* call instruction for Sun ABI GD sequence */
R_386_TLS_GD_POP R_386 = 27 /* popl instruction for Sun ABI GD sequence */
R_386_TLS_LDM_32 R_386 = 28 /* 32 bit offset to GOT (index,zero) pair */
R_386_TLS_LDM_PUSH R_386 = 29 /* pushl instruction for Sun ABI LD sequence */
R_386_TLS_LDM_CALL R_386 = 30 /* call instruction for Sun ABI LD sequence */
R_386_TLS_LDM_POP R_386 = 31 /* popl instruction for Sun ABI LD sequence */
R_386_TLS_LDO_32 R_386 = 32 /* 32 bit offset from start of TLS block */
R_386_TLS_IE_32 R_386 = 33 /* 32 bit offset to GOT static TLS offset entry */
R_386_TLS_LE_32 R_386 = 34 /* 32 bit offset within static TLS block */
R_386_TLS_DTPMOD32 R_386 = 35 /* GOT entry containing TLS index */
R_386_TLS_DTPOFF32 R_386 = 36 /* GOT entry containing TLS offset */
R_386_TLS_TPOFF32 R_386 = 37 /* GOT entry of -ve static TLS offset */
R_386_SIZE32 R_386 = 38
R_386_TLS_GOTDESC R_386 = 39
R_386_TLS_DESC_CALL R_386 = 40
R_386_TLS_DESC R_386 = 41
R_386_IRELATIVE R_386 = 42
R_386_GOT32X R_386 = 43
)
func (i R_386) GoString() string
func (i R_386) String() string
type R_390 int
Relocation types for s390x processors.
const (
R_390_NONE R_390 = 0
R_390_8 R_390 = 1
R_390_12 R_390 = 2
R_390_16 R_390 = 3
R_390_32 R_390 = 4
R_390_PC32 R_390 = 5
R_390_GOT12 R_390 = 6
R_390_GOT32 R_390 = 7
R_390_PLT32 R_390 = 8
R_390_COPY R_390 = 9
R_390_GLOB_DAT R_390 = 10
R_390_JMP_SLOT R_390 = 11
R_390_RELATIVE R_390 = 12
R_390_GOTOFF R_390 = 13
R_390_GOTPC R_390 = 14
R_390_GOT16 R_390 = 15
R_390_PC16 R_390 = 16
R_390_PC16DBL R_390 = 17
R_390_PLT16DBL R_390 = 18
R_390_PC32DBL R_390 = 19
R_390_PLT32DBL R_390 = 20
R_390_GOTPCDBL R_390 = 21
R_390_64 R_390 = 22
R_390_PC64 R_390 = 23
R_390_GOT64 R_390 = 24
R_390_PLT64 R_390 = 25
R_390_GOTENT R_390 = 26
R_390_GOTOFF16 R_390 = 27
R_390_GOTOFF64 R_390 = 28
R_390_GOTPLT12 R_390 = 29
R_390_GOTPLT16 R_390 = 30
R_390_GOTPLT32 R_390 = 31
R_390_GOTPLT64 R_390 = 32
R_390_GOTPLTENT R_390 = 33
R_390_GOTPLTOFF16 R_390 = 34
R_390_GOTPLTOFF32 R_390 = 35
R_390_GOTPLTOFF64 R_390 = 36
R_390_TLS_LOAD R_390 = 37
R_390_TLS_GDCALL R_390 = 38
R_390_TLS_LDCALL R_390 = 39
R_390_TLS_GD32 R_390 = 40
R_390_TLS_GD64 R_390 = 41
R_390_TLS_GOTIE12 R_390 = 42
R_390_TLS_GOTIE32 R_390 = 43
R_390_TLS_GOTIE64 R_390 = 44
R_390_TLS_LDM32 R_390 = 45
R_390_TLS_LDM64 R_390 = 46
R_390_TLS_IE32 R_390 = 47
R_390_TLS_IE64 R_390 = 48
R_390_TLS_IEENT R_390 = 49
R_390_TLS_LE32 R_390 = 50
R_390_TLS_LE64 R_390 = 51
R_390_TLS_LDO32 R_390 = 52
R_390_TLS_LDO64 R_390 = 53
R_390_TLS_DTPMOD R_390 = 54
R_390_TLS_DTPOFF R_390 = 55
R_390_TLS_TPOFF R_390 = 56
R_390_20 R_390 = 57
R_390_GOT20 R_390 = 58
R_390_GOTPLT20 R_390 = 59
R_390_TLS_GOTIE20 R_390 = 60
)
func (i R_390) GoString() string
func (i R_390) String() string
type R_AARCH64 int
Relocation types for AArch64 (aka arm64)
const (
R_AARCH64_NONE R_AARCH64 = 0
R_AARCH64_P32_ABS32 R_AARCH64 = 1
R_AARCH64_P32_ABS16 R_AARCH64 = 2
R_AARCH64_P32_PREL32 R_AARCH64 = 3
R_AARCH64_P32_PREL16 R_AARCH64 = 4
R_AARCH64_P32_MOVW_UABS_G0 R_AARCH64 = 5
R_AARCH64_P32_MOVW_UABS_G0_NC R_AARCH64 = 6
R_AARCH64_P32_MOVW_UABS_G1 R_AARCH64 = 7
R_AARCH64_P32_MOVW_SABS_G0 R_AARCH64 = 8
R_AARCH64_P32_LD_PREL_LO19 R_AARCH64 = 9
R_AARCH64_P32_ADR_PREL_LO21 R_AARCH64 = 10
R_AARCH64_P32_ADR_PREL_PG_HI21 R_AARCH64 = 11
R_AARCH64_P32_ADD_ABS_LO12_NC R_AARCH64 = 12
R_AARCH64_P32_LDST8_ABS_LO12_NC R_AARCH64 = 13
R_AARCH64_P32_LDST16_ABS_LO12_NC R_AARCH64 = 14
R_AARCH64_P32_LDST32_ABS_LO12_NC R_AARCH64 = 15
R_AARCH64_P32_LDST64_ABS_LO12_NC R_AARCH64 = 16
R_AARCH64_P32_LDST128_ABS_LO12_NC R_AARCH64 = 17
R_AARCH64_P32_TSTBR14 R_AARCH64 = 18
R_AARCH64_P32_CONDBR19 R_AARCH64 = 19
R_AARCH64_P32_JUMP26 R_AARCH64 = 20
R_AARCH64_P32_CALL26 R_AARCH64 = 21
R_AARCH64_P32_GOT_LD_PREL19 R_AARCH64 = 25
R_AARCH64_P32_ADR_GOT_PAGE R_AARCH64 = 26
R_AARCH64_P32_LD32_GOT_LO12_NC R_AARCH64 = 27
R_AARCH64_P32_TLSGD_ADR_PAGE21 R_AARCH64 = 81
R_AARCH64_P32_TLSGD_ADD_LO12_NC R_AARCH64 = 82
R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 103
R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC R_AARCH64 = 104
R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 105
R_AARCH64_P32_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 106
R_AARCH64_P32_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 107
R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 108
R_AARCH64_P32_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 109
R_AARCH64_P32_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 110
R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 111
R_AARCH64_P32_TLSDESC_LD_PREL19 R_AARCH64 = 122
R_AARCH64_P32_TLSDESC_ADR_PREL21 R_AARCH64 = 123
R_AARCH64_P32_TLSDESC_ADR_PAGE21 R_AARCH64 = 124
R_AARCH64_P32_TLSDESC_LD32_LO12_NC R_AARCH64 = 125
R_AARCH64_P32_TLSDESC_ADD_LO12_NC R_AARCH64 = 126
R_AARCH64_P32_TLSDESC_CALL R_AARCH64 = 127
R_AARCH64_P32_COPY R_AARCH64 = 180
R_AARCH64_P32_GLOB_DAT R_AARCH64 = 181
R_AARCH64_P32_JUMP_SLOT R_AARCH64 = 182
R_AARCH64_P32_RELATIVE R_AARCH64 = 183
R_AARCH64_P32_TLS_DTPMOD R_AARCH64 = 184
R_AARCH64_P32_TLS_DTPREL R_AARCH64 = 185
R_AARCH64_P32_TLS_TPREL R_AARCH64 = 186
R_AARCH64_P32_TLSDESC R_AARCH64 = 187
R_AARCH64_P32_IRELATIVE R_AARCH64 = 188
R_AARCH64_NULL R_AARCH64 = 256
R_AARCH64_ABS64 R_AARCH64 = 257
R_AARCH64_ABS32 R_AARCH64 = 258
R_AARCH64_ABS16 R_AARCH64 = 259
R_AARCH64_PREL64 R_AARCH64 = 260
R_AARCH64_PREL32 R_AARCH64 = 261
R_AARCH64_PREL16 R_AARCH64 = 262
R_AARCH64_MOVW_UABS_G0 R_AARCH64 = 263
R_AARCH64_MOVW_UABS_G0_NC R_AARCH64 = 264
R_AARCH64_MOVW_UABS_G1 R_AARCH64 = 265
R_AARCH64_MOVW_UABS_G1_NC R_AARCH64 = 266
R_AARCH64_MOVW_UABS_G2 R_AARCH64 = 267
R_AARCH64_MOVW_UABS_G2_NC R_AARCH64 = 268
R_AARCH64_MOVW_UABS_G3 R_AARCH64 = 269
R_AARCH64_MOVW_SABS_G0 R_AARCH64 = 270
R_AARCH64_MOVW_SABS_G1 R_AARCH64 = 271
R_AARCH64_MOVW_SABS_G2 R_AARCH64 = 272
R_AARCH64_LD_PREL_LO19 R_AARCH64 = 273
R_AARCH64_ADR_PREL_LO21 R_AARCH64 = 274
R_AARCH64_ADR_PREL_PG_HI21 R_AARCH64 = 275
R_AARCH64_ADR_PREL_PG_HI21_NC R_AARCH64 = 276
R_AARCH64_ADD_ABS_LO12_NC R_AARCH64 = 277
R_AARCH64_LDST8_ABS_LO12_NC R_AARCH64 = 278
R_AARCH64_TSTBR14 R_AARCH64 = 279
R_AARCH64_CONDBR19 R_AARCH64 = 280
R_AARCH64_JUMP26 R_AARCH64 = 282
R_AARCH64_CALL26 R_AARCH64 = 283
R_AARCH64_LDST16_ABS_LO12_NC R_AARCH64 = 284
R_AARCH64_LDST32_ABS_LO12_NC R_AARCH64 = 285
R_AARCH64_LDST64_ABS_LO12_NC R_AARCH64 = 286
R_AARCH64_LDST128_ABS_LO12_NC R_AARCH64 = 299
R_AARCH64_GOT_LD_PREL19 R_AARCH64 = 309
R_AARCH64_LD64_GOTOFF_LO15 R_AARCH64 = 310
R_AARCH64_ADR_GOT_PAGE R_AARCH64 = 311
R_AARCH64_LD64_GOT_LO12_NC R_AARCH64 = 312
R_AARCH64_LD64_GOTPAGE_LO15 R_AARCH64 = 313
R_AARCH64_TLSGD_ADR_PREL21 R_AARCH64 = 512
R_AARCH64_TLSGD_ADR_PAGE21 R_AARCH64 = 513
R_AARCH64_TLSGD_ADD_LO12_NC R_AARCH64 = 514
R_AARCH64_TLSGD_MOVW_G1 R_AARCH64 = 515
R_AARCH64_TLSGD_MOVW_G0_NC R_AARCH64 = 516
R_AARCH64_TLSLD_ADR_PREL21 R_AARCH64 = 517
R_AARCH64_TLSLD_ADR_PAGE21 R_AARCH64 = 518
R_AARCH64_TLSIE_MOVW_GOTTPREL_G1 R_AARCH64 = 539
R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC R_AARCH64 = 540
R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 541
R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC R_AARCH64 = 542
R_AARCH64_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 543
R_AARCH64_TLSLE_MOVW_TPREL_G2 R_AARCH64 = 544
R_AARCH64_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 545
R_AARCH64_TLSLE_MOVW_TPREL_G1_NC R_AARCH64 = 546
R_AARCH64_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 547
R_AARCH64_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 548
R_AARCH64_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 549
R_AARCH64_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 550
R_AARCH64_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 551
R_AARCH64_TLSDESC_LD_PREL19 R_AARCH64 = 560
R_AARCH64_TLSDESC_ADR_PREL21 R_AARCH64 = 561
R_AARCH64_TLSDESC_ADR_PAGE21 R_AARCH64 = 562
R_AARCH64_TLSDESC_LD64_LO12_NC R_AARCH64 = 563
R_AARCH64_TLSDESC_ADD_LO12_NC R_AARCH64 = 564
R_AARCH64_TLSDESC_OFF_G1 R_AARCH64 = 565
R_AARCH64_TLSDESC_OFF_G0_NC R_AARCH64 = 566
R_AARCH64_TLSDESC_LDR R_AARCH64 = 567
R_AARCH64_TLSDESC_ADD R_AARCH64 = 568
R_AARCH64_TLSDESC_CALL R_AARCH64 = 569
R_AARCH64_TLSLE_LDST128_TPREL_LO12 R_AARCH64 = 570
R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC R_AARCH64 = 571
R_AARCH64_TLSLD_LDST128_DTPREL_LO12 R_AARCH64 = 572
R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC R_AARCH64 = 573
R_AARCH64_COPY R_AARCH64 = 1024
R_AARCH64_GLOB_DAT R_AARCH64 = 1025
R_AARCH64_JUMP_SLOT R_AARCH64 = 1026
R_AARCH64_RELATIVE R_AARCH64 = 1027
R_AARCH64_TLS_DTPMOD64 R_AARCH64 = 1028
R_AARCH64_TLS_DTPREL64 R_AARCH64 = 1029
R_AARCH64_TLS_TPREL64 R_AARCH64 = 1030
R_AARCH64_TLSDESC R_AARCH64 = 1031
R_AARCH64_IRELATIVE R_AARCH64 = 1032
)
func (i R_AARCH64) GoString() string
func (i R_AARCH64) String() string
type R_ALPHA int
Relocation types for Alpha.
const (
R_ALPHA_NONE R_ALPHA = 0 /* No reloc */
R_ALPHA_REFLONG R_ALPHA = 1 /* Direct 32 bit */
R_ALPHA_REFQUAD R_ALPHA = 2 /* Direct 64 bit */
R_ALPHA_GPREL32 R_ALPHA = 3 /* GP relative 32 bit */
R_ALPHA_LITERAL R_ALPHA = 4 /* GP relative 16 bit w/optimization */
R_ALPHA_LITUSE R_ALPHA = 5 /* Optimization hint for LITERAL */
R_ALPHA_GPDISP R_ALPHA = 6 /* Add displacement to GP */
R_ALPHA_BRADDR R_ALPHA = 7 /* PC+4 relative 23 bit shifted */
R_ALPHA_HINT R_ALPHA = 8 /* PC+4 relative 16 bit shifted */
R_ALPHA_SREL16 R_ALPHA = 9 /* PC relative 16 bit */
R_ALPHA_SREL32 R_ALPHA = 10 /* PC relative 32 bit */
R_ALPHA_SREL64 R_ALPHA = 11 /* PC relative 64 bit */
R_ALPHA_OP_PUSH R_ALPHA = 12 /* OP stack push */
R_ALPHA_OP_STORE R_ALPHA = 13 /* OP stack pop and store */
R_ALPHA_OP_PSUB R_ALPHA = 14 /* OP stack subtract */
R_ALPHA_OP_PRSHIFT R_ALPHA = 15 /* OP stack right shift */
R_ALPHA_GPVALUE R_ALPHA = 16
R_ALPHA_GPRELHIGH R_ALPHA = 17
R_ALPHA_GPRELLOW R_ALPHA = 18
R_ALPHA_IMMED_GP_16 R_ALPHA = 19
R_ALPHA_IMMED_GP_HI32 R_ALPHA = 20
R_ALPHA_IMMED_SCN_HI32 R_ALPHA = 21
R_ALPHA_IMMED_BR_HI32 R_ALPHA = 22
R_ALPHA_IMMED_LO32 R_ALPHA = 23
R_ALPHA_COPY R_ALPHA = 24 /* Copy symbol at runtime */
R_ALPHA_GLOB_DAT R_ALPHA = 25 /* Create GOT entry */
R_ALPHA_JMP_SLOT R_ALPHA = 26 /* Create PLT entry */
R_ALPHA_RELATIVE R_ALPHA = 27 /* Adjust by program base */
)
func (i R_ALPHA) GoString() string
func (i R_ALPHA) String() string
type R_ARM int
Relocation types for ARM.
const (
R_ARM_NONE R_ARM = 0 /* No relocation. */
R_ARM_PC24 R_ARM = 1
R_ARM_ABS32 R_ARM = 2
R_ARM_REL32 R_ARM = 3
R_ARM_PC13 R_ARM = 4
R_ARM_ABS16 R_ARM = 5
R_ARM_ABS12 R_ARM = 6
R_ARM_THM_ABS5 R_ARM = 7
R_ARM_ABS8 R_ARM = 8
R_ARM_SBREL32 R_ARM = 9
R_ARM_THM_PC22 R_ARM = 10
R_ARM_THM_PC8 R_ARM = 11
R_ARM_AMP_VCALL9 R_ARM = 12
R_ARM_SWI24 R_ARM = 13
R_ARM_THM_SWI8 R_ARM = 14
R_ARM_XPC25 R_ARM = 15
R_ARM_THM_XPC22 R_ARM = 16
R_ARM_TLS_DTPMOD32 R_ARM = 17
R_ARM_TLS_DTPOFF32 R_ARM = 18
R_ARM_TLS_TPOFF32 R_ARM = 19
R_ARM_COPY R_ARM = 20 /* Copy data from shared object. */
R_ARM_GLOB_DAT R_ARM = 21 /* Set GOT entry to data address. */
R_ARM_JUMP_SLOT R_ARM = 22 /* Set GOT entry to code address. */
R_ARM_RELATIVE R_ARM = 23 /* Add load address of shared object. */
R_ARM_GOTOFF R_ARM = 24 /* Add GOT-relative symbol address. */
R_ARM_GOTPC R_ARM = 25 /* Add PC-relative GOT table address. */
R_ARM_GOT32 R_ARM = 26 /* Add PC-relative GOT offset. */
R_ARM_PLT32 R_ARM = 27 /* Add PC-relative PLT offset. */
R_ARM_CALL R_ARM = 28
R_ARM_JUMP24 R_ARM = 29
R_ARM_THM_JUMP24 R_ARM = 30
R_ARM_BASE_ABS R_ARM = 31
R_ARM_ALU_PCREL_7_0 R_ARM = 32
R_ARM_ALU_PCREL_15_8 R_ARM = 33
R_ARM_ALU_PCREL_23_15 R_ARM = 34
R_ARM_LDR_SBREL_11_10_NC R_ARM = 35
R_ARM_ALU_SBREL_19_12_NC R_ARM = 36
R_ARM_ALU_SBREL_27_20_CK R_ARM = 37
R_ARM_TARGET1 R_ARM = 38
R_ARM_SBREL31 R_ARM = 39
R_ARM_V4BX R_ARM = 40
R_ARM_TARGET2 R_ARM = 41
R_ARM_PREL31 R_ARM = 42
R_ARM_MOVW_ABS_NC R_ARM = 43
R_ARM_MOVT_ABS R_ARM = 44
R_ARM_MOVW_PREL_NC R_ARM = 45
R_ARM_MOVT_PREL R_ARM = 46
R_ARM_THM_MOVW_ABS_NC R_ARM = 47
R_ARM_THM_MOVT_ABS R_ARM = 48
R_ARM_THM_MOVW_PREL_NC R_ARM = 49
R_ARM_THM_MOVT_PREL R_ARM = 50
R_ARM_THM_JUMP19 R_ARM = 51
R_ARM_THM_JUMP6 R_ARM = 52
R_ARM_THM_ALU_PREL_11_0 R_ARM = 53
R_ARM_THM_PC12 R_ARM = 54
R_ARM_ABS32_NOI R_ARM = 55
R_ARM_REL32_NOI R_ARM = 56
R_ARM_ALU_PC_G0_NC R_ARM = 57
R_ARM_ALU_PC_G0 R_ARM = 58
R_ARM_ALU_PC_G1_NC R_ARM = 59
R_ARM_ALU_PC_G1 R_ARM = 60
R_ARM_ALU_PC_G2 R_ARM = 61
R_ARM_LDR_PC_G1 R_ARM = 62
R_ARM_LDR_PC_G2 R_ARM = 63
R_ARM_LDRS_PC_G0 R_ARM = 64
R_ARM_LDRS_PC_G1 R_ARM = 65
R_ARM_LDRS_PC_G2 R_ARM = 66
R_ARM_LDC_PC_G0 R_ARM = 67
R_ARM_LDC_PC_G1 R_ARM = 68
R_ARM_LDC_PC_G2 R_ARM = 69
R_ARM_ALU_SB_G0_NC R_ARM = 70
R_ARM_ALU_SB_G0 R_ARM = 71
R_ARM_ALU_SB_G1_NC R_ARM = 72
R_ARM_ALU_SB_G1 R_ARM = 73
R_ARM_ALU_SB_G2 R_ARM = 74
R_ARM_LDR_SB_G0 R_ARM = 75
R_ARM_LDR_SB_G1 R_ARM = 76
R_ARM_LDR_SB_G2 R_ARM = 77
R_ARM_LDRS_SB_G0 R_ARM = 78
R_ARM_LDRS_SB_G1 R_ARM = 79
R_ARM_LDRS_SB_G2 R_ARM = 80
R_ARM_LDC_SB_G0 R_ARM = 81
R_ARM_LDC_SB_G1 R_ARM = 82
R_ARM_LDC_SB_G2 R_ARM = 83
R_ARM_MOVW_BREL_NC R_ARM = 84
R_ARM_MOVT_BREL R_ARM = 85
R_ARM_MOVW_BREL R_ARM = 86
R_ARM_THM_MOVW_BREL_NC R_ARM = 87
R_ARM_THM_MOVT_BREL R_ARM = 88
R_ARM_THM_MOVW_BREL R_ARM = 89
R_ARM_TLS_GOTDESC R_ARM = 90
R_ARM_TLS_CALL R_ARM = 91
R_ARM_TLS_DESCSEQ R_ARM = 92
R_ARM_THM_TLS_CALL R_ARM = 93
R_ARM_PLT32_ABS R_ARM = 94
R_ARM_GOT_ABS R_ARM = 95
R_ARM_GOT_PREL R_ARM = 96
R_ARM_GOT_BREL12 R_ARM = 97
R_ARM_GOTOFF12 R_ARM = 98
R_ARM_GOTRELAX R_ARM = 99
R_ARM_GNU_VTENTRY R_ARM = 100
R_ARM_GNU_VTINHERIT R_ARM = 101
R_ARM_THM_JUMP11 R_ARM = 102
R_ARM_THM_JUMP8 R_ARM = 103
R_ARM_TLS_GD32 R_ARM = 104
R_ARM_TLS_LDM32 R_ARM = 105
R_ARM_TLS_LDO32 R_ARM = 106
R_ARM_TLS_IE32 R_ARM = 107
R_ARM_TLS_LE32 R_ARM = 108
R_ARM_TLS_LDO12 R_ARM = 109
R_ARM_TLS_LE12 R_ARM = 110
R_ARM_TLS_IE12GP R_ARM = 111
R_ARM_PRIVATE_0 R_ARM = 112
R_ARM_PRIVATE_1 R_ARM = 113
R_ARM_PRIVATE_2 R_ARM = 114
R_ARM_PRIVATE_3 R_ARM = 115
R_ARM_PRIVATE_4 R_ARM = 116
R_ARM_PRIVATE_5 R_ARM = 117
R_ARM_PRIVATE_6 R_ARM = 118
R_ARM_PRIVATE_7 R_ARM = 119
R_ARM_PRIVATE_8 R_ARM = 120
R_ARM_PRIVATE_9 R_ARM = 121
R_ARM_PRIVATE_10 R_ARM = 122
R_ARM_PRIVATE_11 R_ARM = 123
R_ARM_PRIVATE_12 R_ARM = 124
R_ARM_PRIVATE_13 R_ARM = 125
R_ARM_PRIVATE_14 R_ARM = 126
R_ARM_PRIVATE_15 R_ARM = 127
R_ARM_ME_TOO R_ARM = 128
R_ARM_THM_TLS_DESCSEQ16 R_ARM = 129
R_ARM_THM_TLS_DESCSEQ32 R_ARM = 130
R_ARM_THM_GOT_BREL12 R_ARM = 131
R_ARM_THM_ALU_ABS_G0_NC R_ARM = 132
R_ARM_THM_ALU_ABS_G1_NC R_ARM = 133
R_ARM_THM_ALU_ABS_G2_NC R_ARM = 134
R_ARM_THM_ALU_ABS_G3 R_ARM = 135
R_ARM_IRELATIVE R_ARM = 160
R_ARM_RXPC25 R_ARM = 249
R_ARM_RSBREL32 R_ARM = 250
R_ARM_THM_RPC22 R_ARM = 251
R_ARM_RREL32 R_ARM = 252
R_ARM_RABS32 R_ARM = 253
R_ARM_RPC24 R_ARM = 254
R_ARM_RBASE R_ARM = 255
)
func (i R_ARM) GoString() string
func (i R_ARM) String() string
type R_LARCH int
Relocation types for LoongArch.
const (
R_LARCH_NONE R_LARCH = 0
R_LARCH_32 R_LARCH = 1
R_LARCH_64 R_LARCH = 2
R_LARCH_RELATIVE R_LARCH = 3
R_LARCH_COPY R_LARCH = 4
R_LARCH_JUMP_SLOT R_LARCH = 5
R_LARCH_TLS_DTPMOD32 R_LARCH = 6
R_LARCH_TLS_DTPMOD64 R_LARCH = 7
R_LARCH_TLS_DTPREL32 R_LARCH = 8
R_LARCH_TLS_DTPREL64 R_LARCH = 9
R_LARCH_TLS_TPREL32 R_LARCH = 10
R_LARCH_TLS_TPREL64 R_LARCH = 11
R_LARCH_IRELATIVE R_LARCH = 12
R_LARCH_MARK_LA R_LARCH = 20
R_LARCH_MARK_PCREL R_LARCH = 21
R_LARCH_SOP_PUSH_PCREL R_LARCH = 22
R_LARCH_SOP_PUSH_ABSOLUTE R_LARCH = 23
R_LARCH_SOP_PUSH_DUP R_LARCH = 24
R_LARCH_SOP_PUSH_GPREL R_LARCH = 25
R_LARCH_SOP_PUSH_TLS_TPREL R_LARCH = 26
R_LARCH_SOP_PUSH_TLS_GOT R_LARCH = 27
R_LARCH_SOP_PUSH_TLS_GD R_LARCH = 28
R_LARCH_SOP_PUSH_PLT_PCREL R_LARCH = 29
R_LARCH_SOP_ASSERT R_LARCH = 30
R_LARCH_SOP_NOT R_LARCH = 31
R_LARCH_SOP_SUB R_LARCH = 32
R_LARCH_SOP_SL R_LARCH = 33
R_LARCH_SOP_SR R_LARCH = 34
R_LARCH_SOP_ADD R_LARCH = 35
R_LARCH_SOP_AND R_LARCH = 36
R_LARCH_SOP_IF_ELSE R_LARCH = 37
R_LARCH_SOP_POP_32_S_10_5 R_LARCH = 38
R_LARCH_SOP_POP_32_U_10_12 R_LARCH = 39
R_LARCH_SOP_POP_32_S_10_12 R_LARCH = 40
R_LARCH_SOP_POP_32_S_10_16 R_LARCH = 41
R_LARCH_SOP_POP_32_S_10_16_S2 R_LARCH = 42
R_LARCH_SOP_POP_32_S_5_20 R_LARCH = 43
R_LARCH_SOP_POP_32_S_0_5_10_16_S2 R_LARCH = 44
R_LARCH_SOP_POP_32_S_0_10_10_16_S2 R_LARCH = 45
R_LARCH_SOP_POP_32_U R_LARCH = 46
R_LARCH_ADD8 R_LARCH = 47
R_LARCH_ADD16 R_LARCH = 48
R_LARCH_ADD24 R_LARCH = 49
R_LARCH_ADD32 R_LARCH = 50
R_LARCH_ADD64 R_LARCH = 51
R_LARCH_SUB8 R_LARCH = 52
R_LARCH_SUB16 R_LARCH = 53
R_LARCH_SUB24 R_LARCH = 54
R_LARCH_SUB32 R_LARCH = 55
R_LARCH_SUB64 R_LARCH = 56
R_LARCH_GNU_VTINHERIT R_LARCH = 57
R_LARCH_GNU_VTENTRY R_LARCH = 58
R_LARCH_B16 R_LARCH = 64
R_LARCH_B21 R_LARCH = 65
R_LARCH_B26 R_LARCH = 66
R_LARCH_ABS_HI20 R_LARCH = 67
R_LARCH_ABS_LO12 R_LARCH = 68
R_LARCH_ABS64_LO20 R_LARCH = 69
R_LARCH_ABS64_HI12 R_LARCH = 70
R_LARCH_PCALA_HI20 R_LARCH = 71
R_LARCH_PCALA_LO12 R_LARCH = 72
R_LARCH_PCALA64_LO20 R_LARCH = 73
R_LARCH_PCALA64_HI12 R_LARCH = 74
R_LARCH_GOT_PC_HI20 R_LARCH = 75
R_LARCH_GOT_PC_LO12 R_LARCH = 76
R_LARCH_GOT64_PC_LO20 R_LARCH = 77
R_LARCH_GOT64_PC_HI12 R_LARCH = 78
R_LARCH_GOT_HI20 R_LARCH = 79
R_LARCH_GOT_LO12 R_LARCH = 80
R_LARCH_GOT64_LO20 R_LARCH = 81
R_LARCH_GOT64_HI12 R_LARCH = 82
R_LARCH_TLS_LE_HI20 R_LARCH = 83
R_LARCH_TLS_LE_LO12 R_LARCH = 84
R_LARCH_TLS_LE64_LO20 R_LARCH = 85
R_LARCH_TLS_LE64_HI12 R_LARCH = 86
R_LARCH_TLS_IE_PC_HI20 R_LARCH = 87
R_LARCH_TLS_IE_PC_LO12 R_LARCH = 88
R_LARCH_TLS_IE64_PC_LO20 R_LARCH = 89
R_LARCH_TLS_IE64_PC_HI12 R_LARCH = 90
R_LARCH_TLS_IE_HI20 R_LARCH = 91
R_LARCH_TLS_IE_LO12 R_LARCH = 92
R_LARCH_TLS_IE64_LO20 R_LARCH = 93
R_LARCH_TLS_IE64_HI12 R_LARCH = 94
R_LARCH_TLS_LD_PC_HI20 R_LARCH = 95
R_LARCH_TLS_LD_HI20 R_LARCH = 96
R_LARCH_TLS_GD_PC_HI20 R_LARCH = 97
R_LARCH_TLS_GD_HI20 R_LARCH = 98
R_LARCH_32_PCREL R_LARCH = 99
R_LARCH_RELAX R_LARCH = 100
R_LARCH_DELETE R_LARCH = 101
R_LARCH_ALIGN R_LARCH = 102
R_LARCH_PCREL20_S2 R_LARCH = 103
R_LARCH_CFA R_LARCH = 104
R_LARCH_ADD6 R_LARCH = 105
R_LARCH_SUB6 R_LARCH = 106
R_LARCH_ADD_ULEB128 R_LARCH = 107
R_LARCH_SUB_ULEB128 R_LARCH = 108
R_LARCH_64_PCREL R_LARCH = 109
)
func (i R_LARCH) GoString() string
func (i R_LARCH) String() string
type R_MIPS int
Relocation types for MIPS.
const (
R_MIPS_NONE R_MIPS = 0
R_MIPS_16 R_MIPS = 1
R_MIPS_32 R_MIPS = 2
R_MIPS_REL32 R_MIPS = 3
R_MIPS_26 R_MIPS = 4
R_MIPS_HI16 R_MIPS = 5 /* high 16 bits of symbol value */
R_MIPS_LO16 R_MIPS = 6 /* low 16 bits of symbol value */
R_MIPS_GPREL16 R_MIPS = 7 /* GP-relative reference */
R_MIPS_LITERAL R_MIPS = 8 /* Reference to literal section */
R_MIPS_GOT16 R_MIPS = 9 /* Reference to global offset table */
R_MIPS_PC16 R_MIPS = 10 /* 16 bit PC relative reference */
R_MIPS_CALL16 R_MIPS = 11 /* 16 bit call through glbl offset tbl */
R_MIPS_GPREL32 R_MIPS = 12
R_MIPS_SHIFT5 R_MIPS = 16
R_MIPS_SHIFT6 R_MIPS = 17
R_MIPS_64 R_MIPS = 18
R_MIPS_GOT_DISP R_MIPS = 19
R_MIPS_GOT_PAGE R_MIPS = 20
R_MIPS_GOT_OFST R_MIPS = 21
R_MIPS_GOT_HI16 R_MIPS = 22
R_MIPS_GOT_LO16 R_MIPS = 23
R_MIPS_SUB R_MIPS = 24
R_MIPS_INSERT_A R_MIPS = 25
R_MIPS_INSERT_B R_MIPS = 26
R_MIPS_DELETE R_MIPS = 27
R_MIPS_HIGHER R_MIPS = 28
R_MIPS_HIGHEST R_MIPS = 29
R_MIPS_CALL_HI16 R_MIPS = 30
R_MIPS_CALL_LO16 R_MIPS = 31
R_MIPS_SCN_DISP R_MIPS = 32
R_MIPS_REL16 R_MIPS = 33
R_MIPS_ADD_IMMEDIATE R_MIPS = 34
R_MIPS_PJUMP R_MIPS = 35
R_MIPS_RELGOT R_MIPS = 36
R_MIPS_JALR R_MIPS = 37
R_MIPS_TLS_DTPMOD32 R_MIPS = 38 /* Module number 32 bit */
R_MIPS_TLS_DTPREL32 R_MIPS = 39 /* Module-relative offset 32 bit */
R_MIPS_TLS_DTPMOD64 R_MIPS = 40 /* Module number 64 bit */
R_MIPS_TLS_DTPREL64 R_MIPS = 41 /* Module-relative offset 64 bit */
R_MIPS_TLS_GD R_MIPS = 42 /* 16 bit GOT offset for GD */
R_MIPS_TLS_LDM R_MIPS = 43 /* 16 bit GOT offset for LDM */
R_MIPS_TLS_DTPREL_HI16 R_MIPS = 44 /* Module-relative offset, high 16 bits */
R_MIPS_TLS_DTPREL_LO16 R_MIPS = 45 /* Module-relative offset, low 16 bits */
R_MIPS_TLS_GOTTPREL R_MIPS = 46 /* 16 bit GOT offset for IE */
R_MIPS_TLS_TPREL32 R_MIPS = 47 /* TP-relative offset, 32 bit */
R_MIPS_TLS_TPREL64 R_MIPS = 48 /* TP-relative offset, 64 bit */
R_MIPS_TLS_TPREL_HI16 R_MIPS = 49 /* TP-relative offset, high 16 bits */
R_MIPS_TLS_TPREL_LO16 R_MIPS = 50 /* TP-relative offset, low 16 bits */
R_MIPS_PC32 R_MIPS = 248 /* 32 bit PC relative reference */
)
func (i R_MIPS) GoString() string
func (i R_MIPS) String() string
type R_PPC int
Relocation types for PowerPC.
Values that are shared by both R_PPC and R_PPC64 are prefixed with
R_POWERPC_ in the ELF standard. For the R_PPC type, the relevant shared
relocations have been renamed with the prefix R_PPC_. The original name
follows the value in a comment.
const (
R_PPC_PLTREL24 R_PPC = 18
R_PPC_LOCAL24PC R_PPC = 23
R_PPC_SDAREL16 R_PPC = 32
R_PPC_EMB_NADDR32 R_PPC = 101
R_PPC_EMB_NADDR16 R_PPC = 102
R_PPC_EMB_NADDR16_LO R_PPC = 103
R_PPC_EMB_NADDR16_HI R_PPC = 104
R_PPC_EMB_NADDR16_HA R_PPC = 105
R_PPC_EMB_SDAI16 R_PPC = 106
R_PPC_EMB_SDA2I16 R_PPC = 107
R_PPC_EMB_SDA2REL R_PPC = 108
R_PPC_EMB_SDA21 R_PPC = 109
R_PPC_EMB_MRKREF R_PPC = 110
R_PPC_EMB_RELSEC16 R_PPC = 111
R_PPC_EMB_RELST_LO R_PPC = 112
R_PPC_EMB_RELST_HI R_PPC = 113
R_PPC_EMB_RELST_HA R_PPC = 114
R_PPC_EMB_BIT_FLD R_PPC = 115
R_PPC_EMB_RELSDA R_PPC = 116
)
func (i R_PPC) GoString() string
func (i R_PPC) String() string
type R_PPC64 int
Relocation types for 64-bit PowerPC or Power Architecture processors.
Values that are shared by both R_PPC and R_PPC64 are prefixed with
R_POWERPC_ in the ELF standard. For the R_PPC64 type, the relevant shared
relocations have been renamed with the prefix R_PPC64_. The original name
follows the value in a comment.
const (
R_PPC64_ADDR64 R_PPC64 = 38
R_PPC64_ADDR16_HIGHER R_PPC64 = 39
R_PPC64_ADDR16_HIGHERA R_PPC64 = 40
R_PPC64_ADDR16_HIGHEST R_PPC64 = 41
R_PPC64_ADDR16_HIGHESTA R_PPC64 = 42
R_PPC64_UADDR64 R_PPC64 = 43
R_PPC64_REL64 R_PPC64 = 44
R_PPC64_PLT64 R_PPC64 = 45
R_PPC64_PLTREL64 R_PPC64 = 46
R_PPC64_TOC16 R_PPC64 = 47
R_PPC64_TOC16_LO R_PPC64 = 48
R_PPC64_TOC16_HI R_PPC64 = 49
R_PPC64_TOC16_HA R_PPC64 = 50
R_PPC64_TOC R_PPC64 = 51
R_PPC64_PLTGOT16 R_PPC64 = 52
R_PPC64_PLTGOT16_LO R_PPC64 = 53
R_PPC64_PLTGOT16_HI R_PPC64 = 54
R_PPC64_PLTGOT16_HA R_PPC64 = 55
R_PPC64_ADDR16_DS R_PPC64 = 56
R_PPC64_ADDR16_LO_DS R_PPC64 = 57
R_PPC64_GOT16_DS R_PPC64 = 58
R_PPC64_GOT16_LO_DS R_PPC64 = 59
R_PPC64_PLT16_LO_DS R_PPC64 = 60
R_PPC64_SECTOFF_DS R_PPC64 = 61
R_PPC64_SECTOFF_LO_DS R_PPC64 = 62
R_PPC64_TOC16_DS R_PPC64 = 63
R_PPC64_TOC16_LO_DS R_PPC64 = 64
R_PPC64_PLTGOT16_DS R_PPC64 = 65
R_PPC64_PLTGOT_LO_DS R_PPC64 = 66
R_PPC64_TPREL16_DS R_PPC64 = 95
R_PPC64_TPREL16_LO_DS R_PPC64 = 96
R_PPC64_TPREL16_HIGHER R_PPC64 = 97
R_PPC64_TPREL16_HIGHERA R_PPC64 = 98
R_PPC64_TPREL16_HIGHEST R_PPC64 = 99
R_PPC64_TPREL16_HIGHESTA R_PPC64 = 100
R_PPC64_DTPREL16_DS R_PPC64 = 101
R_PPC64_DTPREL16_LO_DS R_PPC64 = 102
R_PPC64_DTPREL16_HIGHER R_PPC64 = 103
R_PPC64_DTPREL16_HIGHERA R_PPC64 = 104
R_PPC64_DTPREL16_HIGHEST R_PPC64 = 105
R_PPC64_DTPREL16_HIGHESTA R_PPC64 = 106
R_PPC64_TLSGD R_PPC64 = 107
R_PPC64_TLSLD R_PPC64 = 108
R_PPC64_TOCSAVE R_PPC64 = 109
R_PPC64_ADDR16_HIGH R_PPC64 = 110
R_PPC64_ADDR16_HIGHA R_PPC64 = 111
R_PPC64_TPREL16_HIGH R_PPC64 = 112
R_PPC64_TPREL16_HIGHA R_PPC64 = 113
R_PPC64_DTPREL16_HIGH R_PPC64 = 114
R_PPC64_DTPREL16_HIGHA R_PPC64 = 115
R_PPC64_REL24_NOTOC R_PPC64 = 116
R_PPC64_ADDR64_LOCAL R_PPC64 = 117
R_PPC64_ENTRY R_PPC64 = 118
R_PPC64_PLTSEQ R_PPC64 = 119
R_PPC64_PLTCALL R_PPC64 = 120
R_PPC64_PLTSEQ_NOTOC R_PPC64 = 121
R_PPC64_PLTCALL_NOTOC R_PPC64 = 122
R_PPC64_PCREL_OPT R_PPC64 = 123
R_PPC64_REL24_P9NOTOC R_PPC64 = 124
R_PPC64_D34 R_PPC64 = 128
R_PPC64_D34_LO R_PPC64 = 129
R_PPC64_D34_HI30 R_PPC64 = 130
R_PPC64_D34_HA30 R_PPC64 = 131
R_PPC64_PCREL34 R_PPC64 = 132
R_PPC64_GOT_PCREL34 R_PPC64 = 133
R_PPC64_PLT_PCREL34 R_PPC64 = 134
R_PPC64_PLT_PCREL34_NOTOC R_PPC64 = 135
R_PPC64_ADDR16_HIGHER34 R_PPC64 = 136
R_PPC64_ADDR16_HIGHERA34 R_PPC64 = 137
R_PPC64_ADDR16_HIGHEST34 R_PPC64 = 138
R_PPC64_ADDR16_HIGHESTA34 R_PPC64 = 139
R_PPC64_REL16_HIGHER34 R_PPC64 = 140
R_PPC64_REL16_HIGHERA34 R_PPC64 = 141
R_PPC64_REL16_HIGHEST34 R_PPC64 = 142
R_PPC64_REL16_HIGHESTA34 R_PPC64 = 143
R_PPC64_D28 R_PPC64 = 144
R_PPC64_PCREL28 R_PPC64 = 145
R_PPC64_TPREL34 R_PPC64 = 146
R_PPC64_DTPREL34 R_PPC64 = 147
R_PPC64_GOT_TLSGD_PCREL34 R_PPC64 = 148
R_PPC64_GOT_TLSLD_PCREL34 R_PPC64 = 149
R_PPC64_GOT_TPREL_PCREL34 R_PPC64 = 150
R_PPC64_GOT_DTPREL_PCREL34 R_PPC64 = 151
R_PPC64_REL16_HIGH R_PPC64 = 240
R_PPC64_REL16_HIGHA R_PPC64 = 241
R_PPC64_REL16_HIGHER R_PPC64 = 242
R_PPC64_REL16_HIGHERA R_PPC64 = 243
R_PPC64_REL16_HIGHEST R_PPC64 = 244
R_PPC64_REL16_HIGHESTA R_PPC64 = 245
R_PPC64_JMP_IREL R_PPC64 = 247
R_PPC64_GNU_VTINHERIT R_PPC64 = 253
R_PPC64_GNU_VTENTRY R_PPC64 = 254
)
func (i R_PPC64) GoString() string
func (i R_PPC64) String() string
type R_RISCV int
Relocation types for RISC-V processors.
const (
R_RISCV_NONE R_RISCV = 0 /* No relocation. */
R_RISCV_32 R_RISCV = 1 /* Add 32 bit zero extended symbol value */
R_RISCV_64 R_RISCV = 2 /* Add 64 bit symbol value. */
R_RISCV_RELATIVE R_RISCV = 3 /* Add load address of shared object. */
R_RISCV_COPY R_RISCV = 4 /* Copy data from shared object. */
R_RISCV_JUMP_SLOT R_RISCV = 5 /* Set GOT entry to code address. */
R_RISCV_TLS_DTPMOD32 R_RISCV = 6 /* 32 bit ID of module containing symbol */
R_RISCV_TLS_DTPMOD64 R_RISCV = 7 /* ID of module containing symbol */
R_RISCV_TLS_DTPREL32 R_RISCV = 8 /* 32 bit relative offset in TLS block */
R_RISCV_TLS_DTPREL64 R_RISCV = 9 /* Relative offset in TLS block */
R_RISCV_TLS_TPREL32 R_RISCV = 10 /* 32 bit relative offset in static TLS block */
R_RISCV_TLS_TPREL64 R_RISCV = 11 /* Relative offset in static TLS block */
R_RISCV_BRANCH R_RISCV = 16 /* PC-relative branch */
R_RISCV_JAL R_RISCV = 17 /* PC-relative jump */
R_RISCV_CALL R_RISCV = 18 /* PC-relative call */
R_RISCV_CALL_PLT R_RISCV = 19 /* PC-relative call (PLT) */
R_RISCV_GOT_HI20 R_RISCV = 20 /* PC-relative GOT reference */
R_RISCV_TLS_GOT_HI20 R_RISCV = 21 /* PC-relative TLS IE GOT offset */
R_RISCV_TLS_GD_HI20 R_RISCV = 22 /* PC-relative TLS GD reference */
R_RISCV_PCREL_HI20 R_RISCV = 23 /* PC-relative reference */
R_RISCV_PCREL_LO12_I R_RISCV = 24 /* PC-relative reference */
R_RISCV_PCREL_LO12_S R_RISCV = 25 /* PC-relative reference */
R_RISCV_HI20 R_RISCV = 26 /* Absolute address */
R_RISCV_LO12_I R_RISCV = 27 /* Absolute address */
R_RISCV_LO12_S R_RISCV = 28 /* Absolute address */
R_RISCV_TPREL_HI20 R_RISCV = 29 /* TLS LE thread offset */
R_RISCV_TPREL_LO12_I R_RISCV = 30 /* TLS LE thread offset */
R_RISCV_TPREL_LO12_S R_RISCV = 31 /* TLS LE thread offset */
R_RISCV_TPREL_ADD R_RISCV = 32 /* TLS LE thread usage */
R_RISCV_ADD8 R_RISCV = 33 /* 8-bit label addition */
R_RISCV_ADD16 R_RISCV = 34 /* 16-bit label addition */
R_RISCV_ADD32 R_RISCV = 35 /* 32-bit label addition */
R_RISCV_ADD64 R_RISCV = 36 /* 64-bit label addition */
R_RISCV_SUB8 R_RISCV = 37 /* 8-bit label subtraction */
R_RISCV_SUB16 R_RISCV = 38 /* 16-bit label subtraction */
R_RISCV_SUB32 R_RISCV = 39 /* 32-bit label subtraction */
R_RISCV_SUB64 R_RISCV = 40 /* 64-bit label subtraction */
R_RISCV_GNU_VTINHERIT R_RISCV = 41 /* GNU C++ vtable hierarchy */
R_RISCV_GNU_VTENTRY R_RISCV = 42 /* GNU C++ vtable member usage */
R_RISCV_ALIGN R_RISCV = 43 /* Alignment statement */
R_RISCV_RVC_BRANCH R_RISCV = 44 /* PC-relative branch offset */
R_RISCV_RVC_JUMP R_RISCV = 45 /* PC-relative jump offset */
R_RISCV_RVC_LUI R_RISCV = 46 /* Absolute address */
R_RISCV_GPREL_I R_RISCV = 47 /* GP-relative reference */
R_RISCV_GPREL_S R_RISCV = 48 /* GP-relative reference */
R_RISCV_TPREL_I R_RISCV = 49 /* TP-relative TLS LE load */
R_RISCV_TPREL_S R_RISCV = 50 /* TP-relative TLS LE store */
R_RISCV_RELAX R_RISCV = 51 /* Instruction pair can be relaxed */
R_RISCV_SUB6 R_RISCV = 52 /* Local label subtraction */
R_RISCV_SET6 R_RISCV = 53 /* Local label subtraction */
R_RISCV_SET8 R_RISCV = 54 /* Local label subtraction */
R_RISCV_SET16 R_RISCV = 55 /* Local label subtraction */
R_RISCV_SET32 R_RISCV = 56 /* Local label subtraction */
R_RISCV_32_PCREL R_RISCV = 57 /* 32-bit PC relative */
)
func (i R_RISCV) GoString() string
func (i R_RISCV) String() string
type R_SPARC int
Relocation types for SPARC.
const (
R_SPARC_NONE R_SPARC = 0
R_SPARC_8 R_SPARC = 1
R_SPARC_16 R_SPARC = 2
R_SPARC_32 R_SPARC = 3
R_SPARC_DISP8 R_SPARC = 4
R_SPARC_DISP16 R_SPARC = 5
R_SPARC_DISP32 R_SPARC = 6
R_SPARC_WDISP30 R_SPARC = 7
R_SPARC_WDISP22 R_SPARC = 8
R_SPARC_HI22 R_SPARC = 9
R_SPARC_22 R_SPARC = 10
R_SPARC_13 R_SPARC = 11
R_SPARC_LO10 R_SPARC = 12
R_SPARC_GOT10 R_SPARC = 13
R_SPARC_GOT13 R_SPARC = 14
R_SPARC_GOT22 R_SPARC = 15
R_SPARC_PC10 R_SPARC = 16
R_SPARC_PC22 R_SPARC = 17
R_SPARC_WPLT30 R_SPARC = 18
R_SPARC_COPY R_SPARC = 19
R_SPARC_GLOB_DAT R_SPARC = 20
R_SPARC_JMP_SLOT R_SPARC = 21
R_SPARC_RELATIVE R_SPARC = 22
R_SPARC_UA32 R_SPARC = 23
R_SPARC_PLT32 R_SPARC = 24
R_SPARC_HIPLT22 R_SPARC = 25
R_SPARC_LOPLT10 R_SPARC = 26
R_SPARC_PCPLT32 R_SPARC = 27
R_SPARC_PCPLT22 R_SPARC = 28
R_SPARC_PCPLT10 R_SPARC = 29
R_SPARC_10 R_SPARC = 30
R_SPARC_11 R_SPARC = 31
R_SPARC_64 R_SPARC = 32
R_SPARC_OLO10 R_SPARC = 33
R_SPARC_HH22 R_SPARC = 34
R_SPARC_HM10 R_SPARC = 35
R_SPARC_LM22 R_SPARC = 36
R_SPARC_PC_HH22 R_SPARC = 37
R_SPARC_PC_HM10 R_SPARC = 38
R_SPARC_PC_LM22 R_SPARC = 39
R_SPARC_WDISP16 R_SPARC = 40
R_SPARC_WDISP19 R_SPARC = 41
R_SPARC_GLOB_JMP R_SPARC = 42
R_SPARC_7 R_SPARC = 43
R_SPARC_5 R_SPARC = 44
R_SPARC_6 R_SPARC = 45
R_SPARC_DISP64 R_SPARC = 46
R_SPARC_PLT64 R_SPARC = 47
R_SPARC_HIX22 R_SPARC = 48
R_SPARC_LOX10 R_SPARC = 49
R_SPARC_H44 R_SPARC = 50
R_SPARC_M44 R_SPARC = 51
R_SPARC_L44 R_SPARC = 52
R_SPARC_REGISTER R_SPARC = 53
R_SPARC_UA64 R_SPARC = 54
R_SPARC_UA16 R_SPARC = 55
)
func (i R_SPARC) GoString() string
func (i R_SPARC) String() string
type R_X86_64 int
Relocation types for x86-64.
const (
R_X86_64_NONE R_X86_64 = 0 /* No relocation. */
R_X86_64_64 R_X86_64 = 1 /* Add 64 bit symbol value. */
R_X86_64_PC32 R_X86_64 = 2 /* PC-relative 32 bit signed sym value. */
R_X86_64_GOT32 R_X86_64 = 3 /* PC-relative 32 bit GOT offset. */
R_X86_64_PLT32 R_X86_64 = 4 /* PC-relative 32 bit PLT offset. */
R_X86_64_COPY R_X86_64 = 5 /* Copy data from shared object. */
R_X86_64_GLOB_DAT R_X86_64 = 6 /* Set GOT entry to data address. */
R_X86_64_JMP_SLOT R_X86_64 = 7 /* Set GOT entry to code address. */
R_X86_64_RELATIVE R_X86_64 = 8 /* Add load address of shared object. */
R_X86_64_GOTPCREL R_X86_64 = 9 /* Add 32 bit signed pcrel offset to GOT. */
R_X86_64_32 R_X86_64 = 10 /* Add 32 bit zero extended symbol value */
R_X86_64_32S R_X86_64 = 11 /* Add 32 bit sign extended symbol value */
R_X86_64_16 R_X86_64 = 12 /* Add 16 bit zero extended symbol value */
R_X86_64_PC16 R_X86_64 = 13 /* Add 16 bit signed extended pc relative symbol value */
R_X86_64_8 R_X86_64 = 14 /* Add 8 bit zero extended symbol value */
R_X86_64_PC8 R_X86_64 = 15 /* Add 8 bit signed extended pc relative symbol value */
R_X86_64_DTPMOD64 R_X86_64 = 16 /* ID of module containing symbol */
R_X86_64_DTPOFF64 R_X86_64 = 17 /* Offset in TLS block */
R_X86_64_TPOFF64 R_X86_64 = 18 /* Offset in static TLS block */
R_X86_64_TLSGD R_X86_64 = 19 /* PC relative offset to GD GOT entry */
R_X86_64_TLSLD R_X86_64 = 20 /* PC relative offset to LD GOT entry */
R_X86_64_DTPOFF32 R_X86_64 = 21 /* Offset in TLS block */
R_X86_64_GOTTPOFF R_X86_64 = 22 /* PC relative offset to IE GOT entry */
R_X86_64_TPOFF32 R_X86_64 = 23 /* Offset in static TLS block */
R_X86_64_PC64 R_X86_64 = 24 /* PC relative 64-bit sign extended symbol value. */
R_X86_64_GOTOFF64 R_X86_64 = 25
R_X86_64_GOTPC32 R_X86_64 = 26
R_X86_64_GOT64 R_X86_64 = 27
R_X86_64_GOTPCREL64 R_X86_64 = 28
R_X86_64_GOTPC64 R_X86_64 = 29
R_X86_64_GOTPLT64 R_X86_64 = 30
R_X86_64_PLTOFF64 R_X86_64 = 31
R_X86_64_SIZE32 R_X86_64 = 32
R_X86_64_SIZE64 R_X86_64 = 33
R_X86_64_GOTPC32_TLSDESC R_X86_64 = 34
R_X86_64_TLSDESC_CALL R_X86_64 = 35
R_X86_64_TLSDESC R_X86_64 = 36
R_X86_64_IRELATIVE R_X86_64 = 37
R_X86_64_RELATIVE64 R_X86_64 = 38
R_X86_64_PC32_BND R_X86_64 = 39
R_X86_64_PLT32_BND R_X86_64 = 40
R_X86_64_GOTPCRELX R_X86_64 = 41
R_X86_64_REX_GOTPCRELX R_X86_64 = 42
)
func (i R_X86_64) GoString() string
func (i R_X86_64) String() string
type Rel32 struct {
Off uint32 /* Location to be relocated. */
Info uint32 /* Relocation type and symbol index. */
}
ELF32 Relocations that don't need an addend field.
type Rel64 struct {
Off uint64 /* Location to be relocated. */
Info uint64 /* Relocation type and symbol index. */
}
ELF64 relocations that don't need an addend field.
type Rela32 struct {
Off uint32 /* Location to be relocated. */
Info uint32 /* Relocation type and symbol index. */
Addend int32 /* Addend. */
}
ELF32 Relocations that need an addend field.
type Rela64 struct {
Off uint64 /* Location to be relocated. */
Info uint64 /* Relocation type and symbol index. */
Addend int64 /* Addend. */
}
ELF64 relocations that need an addend field.
type Section struct {
SectionHeader
io.ReaderAt
sr *io.SectionReader
compressionType CompressionType
compressionOffset int64
}
A Section represents a single section in an ELF file.
func (s *Section) Data() ([]byte, error)
Data reads and returns the contents of the ELF section. Even if the section
is stored compressed in the ELF file, Data returns uncompressed data.
For an SHT_NOBITS section, Data always returns a non-nil error.
func (s *Section) Open() io.ReadSeeker
Open returns a new ReadSeeker reading the ELF section. Even if the section
is stored compressed in the ELF file, the ReadSeeker reads uncompressed
data.
For an SHT_NOBITS section, all calls to the opened reader will return a
non-nil error.
type Section32 struct {
Name uint32 /* Section name (index into the section header string table). */
Type uint32 /* Section type. */
Flags uint32 /* Section flags. */
Addr uint32 /* Address in memory image. */
Off uint32 /* Offset in file. */
Size uint32 /* Size in bytes. */
Link uint32 /* Index of a related section. */
Info uint32 /* Depends on section type. */
Addralign uint32 /* Alignment in bytes. */
Entsize uint32 /* Size of each entry in section. */
}
ELF32 Section header.
type Section64 struct {
Name uint32 /* Section name (index into the section header string table). */
Type uint32 /* Section type. */
Flags uint64 /* Section flags. */
Addr uint64 /* Address in memory image. */
Off uint64 /* Offset in file. */
Size uint64 /* Size in bytes. */
Link uint32 /* Index of a related section. */
Info uint32 /* Depends on section type. */
Addralign uint64 /* Alignment in bytes. */
Entsize uint64 /* Size of each entry in section. */
}
ELF64 Section header.
type SectionFlag uint32
Section flags.
const (
SHF_WRITE SectionFlag = 0x1 /* Section contains writable data. */
SHF_ALLOC SectionFlag = 0x2 /* Section occupies memory. */
SHF_EXECINSTR SectionFlag = 0x4 /* Section contains instructions. */
SHF_MERGE SectionFlag = 0x10 /* Section may be merged. */
SHF_STRINGS SectionFlag = 0x20 /* Section contains strings. */
SHF_INFO_LINK SectionFlag = 0x40 /* sh_info holds section index. */
SHF_LINK_ORDER SectionFlag = 0x80 /* Special ordering requirements. */
SHF_OS_NONCONFORMING SectionFlag = 0x100 /* OS-specific processing required. */
SHF_GROUP SectionFlag = 0x200 /* Member of section group. */
SHF_TLS SectionFlag = 0x400 /* Section contains TLS data. */
SHF_COMPRESSED SectionFlag = 0x800 /* Section is compressed. */
SHF_MASKOS SectionFlag = 0x0ff00000 /* OS-specific semantics. */
SHF_MASKPROC SectionFlag = 0xf0000000 /* Processor-specific semantics. */
)
func (i SectionFlag) GoString() string
func (i SectionFlag) String() string
type SectionHeader struct {
Name string
Type SectionType
Flags SectionFlag
Addr uint64
Offset uint64
Size uint64
Link uint32
Info uint32
Addralign uint64
Entsize uint64
FileSize uint64
}
A SectionHeader represents a single ELF section header.
type SectionIndex int
Special section indices.
const (
SHN_UNDEF SectionIndex = 0 /* Undefined, missing, irrelevant. */
SHN_LORESERVE SectionIndex = 0xff00 /* First of reserved range. */
SHN_LOPROC SectionIndex = 0xff00 /* First processor-specific. */
SHN_HIPROC SectionIndex = 0xff1f /* Last processor-specific. */
SHN_LOOS SectionIndex = 0xff20 /* First operating system-specific. */
SHN_HIOS SectionIndex = 0xff3f /* Last operating system-specific. */
SHN_ABS SectionIndex = 0xfff1 /* Absolute values. */
SHN_COMMON SectionIndex = 0xfff2 /* Common data. */
SHN_XINDEX SectionIndex = 0xffff /* Escape; index stored elsewhere. */
SHN_HIRESERVE SectionIndex = 0xffff /* Last of reserved range. */
)
func (i SectionIndex) GoString() string
func (i SectionIndex) String() string
type SectionType uint32
Section type.
const (
SHT_NULL SectionType = 0 /* inactive */
SHT_PROGBITS SectionType = 1 /* program defined information */
SHT_SYMTAB SectionType = 2 /* symbol table section */
SHT_STRTAB SectionType = 3 /* string table section */
SHT_RELA SectionType = 4 /* relocation section with addends */
SHT_HASH SectionType = 5 /* symbol hash table section */
SHT_DYNAMIC SectionType = 6 /* dynamic section */
SHT_NOTE SectionType = 7 /* note section */
SHT_NOBITS SectionType = 8 /* no space section */
SHT_REL SectionType = 9 /* relocation section - no addends */
SHT_SHLIB SectionType = 10 /* reserved - purpose unknown */
SHT_DYNSYM SectionType = 11 /* dynamic symbol table section */
SHT_INIT_ARRAY SectionType = 14 /* Initialization function pointers. */
SHT_FINI_ARRAY SectionType = 15 /* Termination function pointers. */
SHT_PREINIT_ARRAY SectionType = 16 /* Pre-initialization function ptrs. */
SHT_GROUP SectionType = 17 /* Section group. */
SHT_SYMTAB_SHNDX SectionType = 18 /* Section indexes (see SHN_XINDEX). */
SHT_LOOS SectionType = 0x60000000 /* First of OS specific semantics */
SHT_GNU_ATTRIBUTES SectionType = 0x6ffffff5 /* GNU object attributes */
SHT_GNU_HASH SectionType = 0x6ffffff6 /* GNU hash table */
SHT_GNU_LIBLIST SectionType = 0x6ffffff7 /* GNU prelink library list */
SHT_GNU_VERDEF SectionType = 0x6ffffffd /* GNU version definition section */
SHT_GNU_VERNEED SectionType = 0x6ffffffe /* GNU version needs section */
SHT_GNU_VERSYM SectionType = 0x6fffffff /* GNU version symbol table */
SHT_HIOS SectionType = 0x6fffffff /* Last of OS specific semantics */
SHT_LOPROC SectionType = 0x70000000 /* reserved range for processor */
SHT_MIPS_ABIFLAGS SectionType = 0x7000002a /* .MIPS.abiflags */
SHT_HIPROC SectionType = 0x7fffffff /* specific section header types */
SHT_LOUSER SectionType = 0x80000000 /* reserved range for application */
SHT_HIUSER SectionType = 0xffffffff /* specific indexes */
)
func (i SectionType) GoString() string
func (i SectionType) String() string
type Sym32 struct {
Name uint32
Value uint32
Size uint32
Info uint8
Other uint8
Shndx uint16
}
ELF32 Symbol.
type Sym64 struct {
Name uint32 /* String table index of name. */
Info uint8 /* Type and binding information. */
Other uint8 /* Reserved (not used). */
Shndx uint16 /* Section index of symbol. */
Value uint64 /* Symbol value. */
Size uint64 /* Size of associated object. */
}
ELF64 symbol table entries.
type SymBind int
Symbol Binding - ELFNN_ST_BIND - st_info
const (
STB_LOCAL SymBind = 0 /* Local symbol */
STB_GLOBAL SymBind = 1 /* Global symbol */
STB_WEAK SymBind = 2 /* like global - lower precedence */
STB_LOOS SymBind = 10 /* Reserved range for operating system */
STB_HIOS SymBind = 12 /* specific semantics. */
STB_LOPROC SymBind = 13 /* reserved range for processor */
STB_HIPROC SymBind = 15 /* specific semantics. */
)
func ST_BIND(info uint8) SymBind
func (i SymBind) GoString() string
func (i SymBind) String() string
type SymType int
Symbol type - ELFNN_ST_TYPE - st_info
const (
STT_NOTYPE SymType = 0 /* Unspecified type. */
STT_OBJECT SymType = 1 /* Data object. */
STT_FUNC SymType = 2 /* Function. */
STT_SECTION SymType = 3 /* Section. */
STT_FILE SymType = 4 /* Source file. */
STT_COMMON SymType = 5 /* Uninitialized common block. */
STT_TLS SymType = 6 /* TLS object. */
STT_LOOS SymType = 10 /* Reserved range for operating system */
STT_HIOS SymType = 12 /* specific semantics. */
STT_LOPROC SymType = 13 /* reserved range for processor */
STT_HIPROC SymType = 15 /* specific semantics. */
/* Non-standard symbol types. */
STT_RELC SymType = 8 /* Complex relocation expression. */
STT_SRELC SymType = 9 /* Signed complex relocation expression. */
STT_GNU_IFUNC SymType = 10 /* Indirect code object. */
)
func ST_TYPE(info uint8) SymType
func (i SymType) GoString() string
func (i SymType) String() string
type SymVis int
Symbol visibility - ELFNN_ST_VISIBILITY - st_other
const (
STV_DEFAULT SymVis = 0x0 /* Default visibility (see binding). */
STV_INTERNAL SymVis = 0x1 /* Special meaning in relocatable objects. */
STV_HIDDEN SymVis = 0x2 /* Not visible. */
STV_PROTECTED SymVis = 0x3 /* Visible but not preemptible. */
)
func ST_VISIBILITY(other uint8) SymVis
func (i SymVis) GoString() string
func (i SymVis) String() string
type Symbol struct {
Name string
Info, Other byte
VersionScope SymbolVersionScope
VersionIndex int16
Section SectionIndex
Value, Size uint64
Version string
Library string
}
A Symbol represents an entry in an ELF symbol table section.
type SymbolVersionScope byte
SymbolVersionScope describes the version in which a Symbol is defined.
This is only used for the dynamic symbol table.
const (
)
type Type uint16
Type is found in Header.Type.
const (
ET_NONE Type = 0 /* Unknown type. */
ET_REL Type = 1 /* Relocatable. */
ET_EXEC Type = 2 /* Executable. */
ET_DYN Type = 3 /* Shared object. */
ET_CORE Type = 4 /* Core file. */
ET_LOOS Type = 0xfe00 /* First operating system specific. */
ET_HIOS Type = 0xfeff /* Last operating system-specific. */
ET_LOPROC Type = 0xff00 /* First processor-specific. */
ET_HIPROC Type = 0xffff /* Last processor-specific. */
)
func (i Type) GoString() string
func (i Type) String() string
type Version byte
Version is found in Header.Ident[EI_VERSION] and Header.Version.
const (
EV_NONE Version = 0
EV_CURRENT Version = 1
)
func (i Version) GoString() string
func (i Version) String() string
type errorReader struct {
error
}
errorReader returns error from all operations.
func (r errorReader) Close() error
func (r errorReader) Read(p []byte) (n int, err error)
func (r errorReader) ReadAt(p []byte, off int64) (n int, err error)
func (r errorReader) Seek(offset int64, whence int) (int64, error)
type intName struct {
i uint32
s string
}
type nobitsSectionReader struct{}
func (*nobitsSectionReader) ReadAt(p []byte, off int64) (n int, err error)
type readSeekerFromReader struct {
reset func() (io.Reader, error)
r io.Reader
size int64
offset int64
}
readSeekerFromReader converts an io.Reader into an io.ReadSeeker. In general
Seek may not be efficient, but it is optimized for common cases such as
seeking to the end to find the length of the data.
func (r *readSeekerFromReader) Read(p []byte) (n int, err error)
func (r *readSeekerFromReader) Seek(offset int64, whence int) (int64, error)
func (r *readSeekerFromReader) start()
debug/gosym
func walksymtab(data []byte, fn func(sym) error) error
TYPES
type DecodingError struct {
off int
msg string
val any
}
DecodingError represents an error during the decoding of the symbol table.
func (e *DecodingError) Error() string
type Func struct {
Entry uint64
*Sym
End uint64
FrameSize int
LineTable *LineTable
Obj *Obj
}
A Func collects information about a single function.
type LineTable struct {
Data []byte
PC uint64
Line int
mu sync.Mutex
version version
binary binary.ByteOrder
quantum uint32
ptrsize uint32
funcnametab []byte
cutab []byte
funcdata []byte
functab []byte
nfunctab uint32
filetab []byte
nfiletab uint32
fileMap map[string]uint32
}
A LineTable is a data structure mapping program counters to line numbers.
In Go 1.1 and earlier, each function (represented by a Func) had its own
LineTable, and the line number corresponded to a numbering of all source
lines in the program, across all files. That absolute line number would then
have to be converted separately to a file name and line number within the
file.
In Go 1.2, the format of the data changed so that there is a single
LineTable for the entire program, shared by all Funcs, and there are no
absolute line numbers, just line numbers within specific files.
For the most part, LineTable's methods should be treated as an internal
detail of the package; callers should use the methods on Table instead.
func NewLineTable(data []byte, text uint64) *LineTable
NewLineTable returns a new PC/line table corresponding to the encoded data.
Text must be the start address of the corresponding text segment, with the
exact value stored in the 'runtime.text' symbol. This value may differ from
the start address of the text segment if binary was built with cgo enabled.
func (t *LineTable) LineToPC(line int, maxpc uint64) uint64
LineToPC returns the program counter for the given line number, considering
only program counters before maxpc.
Deprecated: Use Table's LineToPC method instead.
func (t *LineTable) PCToLine(pc uint64) int
PCToLine returns the line number for the given program counter.
Deprecated: Use Table's PCToLine method instead.
func (t *LineTable) findFileLine(entry uint64, filetab, linetab uint32, filenum, line int32, cutab []byte) uint64
findFileLine scans one function in the binary looking for a program counter
in the given file on the given line. It does so by running the pc-value
tables mapping program counter to file number. Since most functions
come from a single file, these are usually short and quick to scan.
If a file match is found, then the code goes to the expense of looking for a
simultaneous line number match.
func (t *LineTable) findFunc(pc uint64) funcData
findFunc returns the funcData corresponding to the given program counter.
func (t *LineTable) funcData(i uint32) funcData
funcData returns the ith funcData in t.functab.
func (t *LineTable) funcName(off uint32) string
funcName returns the name of the function found at off.
func (t *LineTable) funcTab() funcTab
funcTab returns t's funcTab.
func (t *LineTable) functabFieldSize() int
functabFieldSize returns the size in bytes of a single functab field.
func (t *LineTable) go12Funcs() []Func
go12Funcs returns a slice of Funcs derived from the Go 1.2+ pcln table.
func (t *LineTable) go12LineToPC(file string, line int) (pc uint64)
go12LineToPC maps a (file, line) pair to a program counter for the Go 1.2+
pcln table.
func (t *LineTable) go12MapFiles(m map[string]*Obj, obj *Obj)
go12MapFiles adds to m a key for every file in the Go 1.2 LineTable.
Every key maps to obj. That's not a very interesting map, but it provides a
way for callers to obtain the list of files in the program.
func (t *LineTable) go12PCToFile(pc uint64) (file string)
go12PCToFile maps program counter to file name for the Go 1.2+ pcln table.
func (t *LineTable) go12PCToLine(pc uint64) (line int)
go12PCToLine maps program counter to line number for the Go 1.2+ pcln table.
func (t *LineTable) initFileMap()
initFileMap initializes the map from file name to file number.
func (t *LineTable) isGo12() bool
isGo12 reports whether this is a Go 1.2 (or later) symbol table.
func (t *LineTable) parse(targetPC uint64, targetLine int) (b []byte, pc uint64, line int)
func (t *LineTable) parsePclnTab()
parsePclnTab parses the pclntab, setting the version.
func (t *LineTable) pcvalue(off uint32, entry, targetpc uint64) int32
pcvalue reports the value associated with the target pc. off is the offset
to the beginning of the pc-value table, and entry is the start PC for the
corresponding function.
func (t *LineTable) readvarint(pp *[]byte) uint32
readvarint reads, removes, and returns a varint from *pp.
func (t *LineTable) slice(pc uint64) *LineTable
func (t *LineTable) step(p *[]byte, pc *uint64, val *int32, first bool) bool
step advances to the next pc, value pair in the encoded table.
func (t *LineTable) string(off uint32) string
string returns a Go string found at off.
func (t *LineTable) stringFrom(arr []byte, off uint32) string
stringFrom returns a Go string found at off from a position.
func (t *LineTable) uintptr(b []byte) uint64
uintptr returns the pointer-sized value encoded at b. The pointer size is
dictated by the table being read.
type Obj struct {
Funcs []Func
}
An Obj represents a collection of functions in a symbol table.
The exact method of division of a binary into separate Objs is an internal
detail of the symbol table format.
In early versions of Go each source file became a different Obj.
In Go 1 and Go 1.1, each package produced one Obj for all Go sources and one
Obj per C source file.
In Go 1.2, there is a single Obj for the entire program.
func (o *Obj) alineFromLine(path string, line int) (int, error)
func (o *Obj) lineFromAline(aline int) (string, int)
type Sym struct {
Value uint64
Type byte
Name string
GoType uint64
Func *Func
goVersion version
}
A Sym represents a single symbol table entry.
func (s *Sym) BaseName() string
BaseName returns the symbol name without the package or receiver name.
func (s *Sym) PackageName() string
PackageName returns the package part of the symbol name, or the empty string
if there is none.
func (s *Sym) ReceiverName() string
ReceiverName returns the receiver type name of this symbol, or the empty
string if there is none. A receiver name is only detected in the case that
s.Name is fully-specified with a package name.
func (s *Sym) Static() bool
Static reports whether this symbol is static (not visible outside its file).
func (s *Sym) nameWithoutInst() string
nameWithoutInst returns s.Name if s.Name has no brackets (does not reference
an instantiated type, function, or method). If s.Name contains brackets,
then it returns s.Name with all the contents between (and including) the
outermost left and right bracket removed. This is useful to ignore any
extra slashes or dots inside the brackets from the string searches below,
where needed.
type Table struct {
Funcs []Func
}
Table represents a Go symbol table. It stores all of the symbols decoded
from the program and provides methods to translate between symbols, names,
and addresses.
func NewTable(symtab []byte, pcln *LineTable) (*Table, error)
NewTable decodes the Go symbol table (the ".gosymtab" section in ELF),
returning an in-memory representation. Starting with Go 1.3, the Go symbol
table no longer includes symbol data.
func (t *Table) LineToPC(file string, line int) (pc uint64, fn *Func, err error)
LineToPC looks up the first program counter on the given line in the named
file. It returns UnknownFileError or UnknownLineError if there is an error
looking up this line.
func (t *Table) LookupFunc(name string) *Func
LookupFunc returns the text, data, or bss symbol with the given name,
or nil if no such symbol is found.
func (t *Table) LookupSym(name string) *Sym
LookupSym returns the text, data, or bss symbol with the given name,
or nil if no such symbol is found.
func (t *Table) PCToFunc(pc uint64) *Func
PCToFunc returns the function containing the program counter pc, or nil if
there is no such function.
func (t *Table) PCToLine(pc uint64) (file string, line int, fn *Func)
PCToLine looks up line number information for a program counter. If there is
no information, it returns fn == nil.
func (t *Table) SymByAddr(addr uint64) *Sym
SymByAddr returns the text, data, or bss symbol starting at the given
address.
type UnknownFileError string
UnknownFileError represents a failure to find the specific file in the
symbol table.
func (e UnknownFileError) Error() string
type UnknownLineError struct {
File string
Line int
}
UnknownLineError represents a failure to map a line to a program counter,
either because the line is beyond the bounds of the file or because there is
no code on the given line.
func (e *UnknownLineError) Error() string
type funcData struct {
}
funcData is memory corresponding to an _func struct.
func (f funcData) IsZero() bool
IsZero reports whether f is the zero value.
func (f funcData) cuOffset() uint32
func (f funcData) deferreturn() uint32
func (f *funcData) entryPC() uint64
entryPC returns the func's entry PC.
func (f funcData) field(n uint32) uint32
field returns the nth field of the _func struct. It panics if n == 0 or
n > 9; for n == 0, call f.entryPC. Most callers should use a named field
accessor (just above).
func (f funcData) nameOff() uint32
func (f funcData) pcfile() uint32
func (f funcData) pcln() uint32
type funcTab struct {
*LineTable
}
funcTab is memory corresponding to a slice of functab structs, followed by
an invalid PC. A functab struct is a PC and a func offset.
func (f funcTab) Count() int
Count returns the number of func entries in f.
func (f funcTab) funcOff(i int) uint64
funcOff returns the funcdata offset of the i'th func in f.
func (f funcTab) pc(i int) uint64
pc returns the PC of the i'th func in f.
func (f funcTab) uint(b []byte) uint64
uint returns the uint stored at b.
type sym struct {
value uint64
gotype uint64
typ byte
name []byte
}
type version int
version of the pclntab
const (
verUnknown version = iota
ver11
ver12
ver116
ver118
ver120
)
debug/macho
func _()
func cstring(b []byte) string
func stringName(i uint32, names []intName, goSyntax bool) string
TYPES
type Cpu uint32
A Cpu is a Mach-O cpu type.
const (
Cpu386 Cpu = 7
CpuAmd64 Cpu = Cpu386 | cpuArch64
CpuArm Cpu = 12
CpuArm64 Cpu = CpuArm | cpuArch64
CpuPpc Cpu = 18
CpuPpc64 Cpu = CpuPpc | cpuArch64
)
func (i Cpu) GoString() string
func (i Cpu) String() string
type Dylib struct {
LoadBytes
Name string
Time uint32
CurrentVersion uint32
CompatVersion uint32
}
A Dylib represents a Mach-O load dynamic library command.
type DylibCmd struct {
Cmd LoadCmd
Len uint32
Name uint32
Time uint32
CurrentVersion uint32
CompatVersion uint32
}
A DylibCmd is a Mach-O load dynamic library command.
type Dysymtab struct {
LoadBytes
DysymtabCmd
}
A Dysymtab represents a Mach-O dynamic symbol table command.
type DysymtabCmd struct {
Cmd LoadCmd
Len uint32
Ilocalsym uint32
Nlocalsym uint32
Iextdefsym uint32
Nextdefsym uint32
Iundefsym uint32
Nundefsym uint32
Tocoffset uint32
Ntoc uint32
Modtaboff uint32
Nmodtab uint32
Extrefsymoff uint32
Nextrefsyms uint32
Indirectsymoff uint32
Nindirectsyms uint32
Extreloff uint32
Nextrel uint32
Locreloff uint32
Nlocrel uint32
}
A DysymtabCmd is a Mach-O dynamic symbol table command.
type FatArch struct {
FatArchHeader
*File
}
A FatArch is a Mach-O File inside a FatFile.
type FatArchHeader struct {
Cpu Cpu
SubCpu uint32
Offset uint32
Size uint32
Align uint32
}
A FatArchHeader represents a fat header for a specific image architecture.
type FatFile struct {
Magic uint32
Arches []FatArch
closer io.Closer
}
A FatFile is a Mach-O universal binary that contains at least one
architecture.
func NewFatFile(r io.ReaderAt) (*FatFile, error)
NewFatFile creates a new FatFile for accessing all the Mach-O images in a
universal binary. The Mach-O binary is expected to start at position 0 in
the ReaderAt.
func OpenFat(name string) (*FatFile, error)
OpenFat opens the named file using os.Open and prepares it for use as a
Mach-O universal binary.
func (ff *FatFile) Close() error
type File struct {
FileHeader
ByteOrder binary.ByteOrder
Loads []Load
Sections []*Section
Symtab *Symtab
Dysymtab *Dysymtab
closer io.Closer
}
A File represents an open Mach-O file.
func NewFile(r io.ReaderAt) (*File, error)
NewFile creates a new File for accessing a Mach-O binary in an underlying
reader. The Mach-O binary is expected to start at position 0 in the
ReaderAt.
func Open(name string) (*File, error)
Open opens the named file using os.Open and prepares it for use as a Mach-O
binary.
func (f *File) Close() error
Close closes the File. If the File was created using NewFile directly
instead of Open, Close has no effect.
func (f *File) DWARF() (*dwarf.Data, error)
DWARF returns the DWARF debug information for the Mach-O file.
func (f *File) ImportedLibraries() ([]string, error)
ImportedLibraries returns the paths of all libraries referred to by the
binary f that are expected to be linked with the binary at dynamic link
time.
func (f *File) ImportedSymbols() ([]string, error)
ImportedSymbols returns the names of all symbols referred to by the binary f
that are expected to be satisfied by other libraries at dynamic load time.
func (f *File) Section(name string) *Section
Section returns the first section with the given name, or nil if no such
section exists.
func (f *File) Segment(name string) *Segment
Segment returns the first Segment with the given name, or nil if no such
segment exists.
func (f *File) parseSymtab(symdat, strtab, cmddat []byte, hdr *SymtabCmd, offset int64) (*Symtab, error)
func (f *File) pushSection(sh *Section, r io.ReaderAt) error
type FileHeader struct {
Magic uint32
Cpu Cpu
SubCpu uint32
Type Type
Ncmd uint32
Cmdsz uint32
Flags uint32
}
A FileHeader represents a Mach-O file header.
type FormatError struct {
off int64
msg string
val any
}
FormatError is returned by some operations if the data does not have the
correct format for an object file.
func (e *FormatError) Error() string
type Load interface {
Raw() []byte
}
A Load represents any Mach-O load command.
type LoadBytes []byte
A LoadBytes is the uninterpreted bytes of a Mach-O load command.
func (b LoadBytes) Raw() []byte
type LoadCmd uint32
A LoadCmd is a Mach-O load command.
const (
LoadCmdSegment LoadCmd = 0x1
LoadCmdSymtab LoadCmd = 0x2
LoadCmdThread LoadCmd = 0x4
LoadCmdDysymtab LoadCmd = 0xb
LoadCmdSegment64 LoadCmd = 0x19
LoadCmdRpath LoadCmd = 0x8000001c
)
func (i LoadCmd) GoString() string
func (i LoadCmd) String() string
type Nlist32 struct {
Name uint32
Type uint8
Sect uint8
Desc uint16
Value uint32
}
An Nlist32 is a Mach-O 32-bit symbol table entry.
type Nlist64 struct {
Name uint32
Type uint8
Sect uint8
Desc uint16
Value uint64
}
An Nlist64 is a Mach-O 64-bit symbol table entry.
type Regs386 struct {
AX uint32
BX uint32
CX uint32
DX uint32
DI uint32
SI uint32
BP uint32
SP uint32
SS uint32
FLAGS uint32
IP uint32
CS uint32
DS uint32
ES uint32
FS uint32
GS uint32
}
Regs386 is the Mach-O 386 register structure.
type RegsAMD64 struct {
AX uint64
BX uint64
CX uint64
DX uint64
DI uint64
SI uint64
BP uint64
SP uint64
R8 uint64
R9 uint64
R10 uint64
R11 uint64
R12 uint64
R13 uint64
R14 uint64
R15 uint64
IP uint64
FLAGS uint64
CS uint64
FS uint64
GS uint64
}
RegsAMD64 is the Mach-O AMD64 register structure.
type Reloc struct {
Addr uint32
Value uint32
Type uint8
Pcrel bool
Scattered bool
}
A Reloc represents a Mach-O relocation.
type RelocTypeARM int
const (
ARM_RELOC_VANILLA RelocTypeARM = 0
ARM_RELOC_PAIR RelocTypeARM = 1
ARM_RELOC_SECTDIFF RelocTypeARM = 2
ARM_RELOC_LOCAL_SECTDIFF RelocTypeARM = 3
ARM_RELOC_PB_LA_PTR RelocTypeARM = 4
ARM_RELOC_BR24 RelocTypeARM = 5
ARM_THUMB_RELOC_BR22 RelocTypeARM = 6
ARM_THUMB_32BIT_BRANCH RelocTypeARM = 7
ARM_RELOC_HALF RelocTypeARM = 8
ARM_RELOC_HALF_SECTDIFF RelocTypeARM = 9
)
func (r RelocTypeARM) GoString() string
func (i RelocTypeARM) String() string
type RelocTypeARM64 int
const (
ARM64_RELOC_UNSIGNED RelocTypeARM64 = 0
ARM64_RELOC_SUBTRACTOR RelocTypeARM64 = 1
ARM64_RELOC_BRANCH26 RelocTypeARM64 = 2
ARM64_RELOC_PAGE21 RelocTypeARM64 = 3
ARM64_RELOC_PAGEOFF12 RelocTypeARM64 = 4
ARM64_RELOC_GOT_LOAD_PAGE21 RelocTypeARM64 = 5
ARM64_RELOC_GOT_LOAD_PAGEOFF12 RelocTypeARM64 = 6
ARM64_RELOC_POINTER_TO_GOT RelocTypeARM64 = 7
ARM64_RELOC_TLVP_LOAD_PAGE21 RelocTypeARM64 = 8
ARM64_RELOC_TLVP_LOAD_PAGEOFF12 RelocTypeARM64 = 9
ARM64_RELOC_ADDEND RelocTypeARM64 = 10
)
func (r RelocTypeARM64) GoString() string
func (i RelocTypeARM64) String() string
type RelocTypeGeneric int
const (
GENERIC_RELOC_VANILLA RelocTypeGeneric = 0
GENERIC_RELOC_PAIR RelocTypeGeneric = 1
GENERIC_RELOC_SECTDIFF RelocTypeGeneric = 2
GENERIC_RELOC_PB_LA_PTR RelocTypeGeneric = 3
GENERIC_RELOC_LOCAL_SECTDIFF RelocTypeGeneric = 4
GENERIC_RELOC_TLV RelocTypeGeneric = 5
)
func (r RelocTypeGeneric) GoString() string
func (i RelocTypeGeneric) String() string
type RelocTypeX86_64 int
const (
X86_64_RELOC_UNSIGNED RelocTypeX86_64 = 0
X86_64_RELOC_SIGNED RelocTypeX86_64 = 1
X86_64_RELOC_BRANCH RelocTypeX86_64 = 2
X86_64_RELOC_GOT_LOAD RelocTypeX86_64 = 3
X86_64_RELOC_GOT RelocTypeX86_64 = 4
X86_64_RELOC_SUBTRACTOR RelocTypeX86_64 = 5
X86_64_RELOC_SIGNED_1 RelocTypeX86_64 = 6
X86_64_RELOC_SIGNED_2 RelocTypeX86_64 = 7
X86_64_RELOC_SIGNED_4 RelocTypeX86_64 = 8
X86_64_RELOC_TLV RelocTypeX86_64 = 9
)
func (r RelocTypeX86_64) GoString() string
func (i RelocTypeX86_64) String() string
type Rpath struct {
LoadBytes
Path string
}
A Rpath represents a Mach-O rpath command.
type RpathCmd struct {
Cmd LoadCmd
Len uint32
Path uint32
}
A RpathCmd is a Mach-O rpath command.
type Section struct {
SectionHeader
Relocs []Reloc
io.ReaderAt
sr *io.SectionReader
}
func (s *Section) Data() ([]byte, error)
Data reads and returns the contents of the Mach-O section.
func (s *Section) Open() io.ReadSeeker
Open returns a new ReadSeeker reading the Mach-O section.
type Section32 struct {
Name [16]byte
Seg [16]byte
Addr uint32
Size uint32
Offset uint32
Align uint32
Reloff uint32
Nreloc uint32
Flags uint32
Reserve1 uint32
Reserve2 uint32
}
A Section32 is a 32-bit Mach-O section header.
type Section64 struct {
Name [16]byte
Seg [16]byte
Addr uint64
Size uint64
Offset uint32
Align uint32
Reloff uint32
Nreloc uint32
Flags uint32
Reserve1 uint32
Reserve2 uint32
Reserve3 uint32
}
A Section64 is a 64-bit Mach-O section header.
type SectionHeader struct {
Name string
Seg string
Addr uint64
Size uint64
Offset uint32
Align uint32
Reloff uint32
Nreloc uint32
Flags uint32
}
type Segment struct {
LoadBytes
SegmentHeader
io.ReaderAt
sr *io.SectionReader
}
A Segment represents a Mach-O 32-bit or 64-bit load segment command.
func (s *Segment) Data() ([]byte, error)
Data reads and returns the contents of the segment.
func (s *Segment) Open() io.ReadSeeker
Open returns a new ReadSeeker reading the segment.
type Segment32 struct {
Cmd LoadCmd
Len uint32
Name [16]byte
Addr uint32
Memsz uint32
Offset uint32
Filesz uint32
Maxprot uint32
Prot uint32
Nsect uint32
Flag uint32
}
A Segment32 is a 32-bit Mach-O segment load command.
type Segment64 struct {
Cmd LoadCmd
Len uint32
Name [16]byte
Addr uint64
Memsz uint64
Offset uint64
Filesz uint64
Maxprot uint32
Prot uint32
Nsect uint32
Flag uint32
}
A Segment64 is a 64-bit Mach-O segment load command.
type SegmentHeader struct {
Cmd LoadCmd
Len uint32
Name string
Addr uint64
Memsz uint64
Offset uint64
Filesz uint64
Maxprot uint32
Prot uint32
Nsect uint32
Flag uint32
}
A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment
command.
type Symbol struct {
Name string
Type uint8
Sect uint8
Desc uint16
Value uint64
}
A Symbol is a Mach-O 32-bit or 64-bit symbol table entry.
type Symtab struct {
LoadBytes
SymtabCmd
Syms []Symbol
}
A Symtab represents a Mach-O symbol table command.
type SymtabCmd struct {
Cmd LoadCmd
Len uint32
Symoff uint32
Nsyms uint32
Stroff uint32
Strsize uint32
}
A SymtabCmd is a Mach-O symbol table command.
type Thread struct {
Cmd LoadCmd
Len uint32
Type uint32
Data []uint32
}
A Thread is a Mach-O thread state command.
type Type uint32
A Type is the Mach-O file type, e.g. an object file, executable, or dynamic
library.
const (
TypeObj Type = 1
TypeExec Type = 2
TypeDylib Type = 6
TypeBundle Type = 8
)
func (t Type) GoString() string
func (t Type) String() string
type intName struct {
i uint32
s string
}
type relocInfo struct {
Addr uint32
Symnum uint32
}
debug/pe
func cstring(b []byte) string
cstring converts ASCII byte sequence b to string. It stops once it finds 0
or reaches end of b.
func getString(section []byte, start int) (string, bool)
getString extracts a string from symbol string table.
func isSymNameOffset(name [8]byte) (bool, uint32)
isSymNameOffset checks symbol name if it is encoded as offset into string
table.
func readOptionalHeader(r io.ReadSeeker, sz uint16) (any, error)
readOptionalHeader accepts an io.ReadSeeker pointing to optional header in
the PE file and its size as seen in the file header. It parses the given
size of bytes and returns optional header. It infers whether the bytes being
parsed refer to 32 bit or 64 bit version of optional header.
TYPES
type COFFSymbol struct {
Name [8]uint8
Value uint32
SectionNumber int16
Type uint16
StorageClass uint8
NumberOfAuxSymbols uint8
}
COFFSymbol represents single COFF symbol table record.
func readCOFFSymbols(fh *FileHeader, r io.ReadSeeker) ([]COFFSymbol, error)
readCOFFSymbols reads in the symbol table for a PE file, returning a slice
of COFFSymbol objects. The PE format includes both primary symbols (whose
fields are described by COFFSymbol above) and auxiliary symbols; all symbols
are 18 bytes in size. The auxiliary symbols for a given primary symbol are
placed following it in the array, e.g.
...
k+0: regular sym k
k+1: 1st aux symbol for k
k+2: 2nd aux symbol for k
k+3: regular sym k+3
k+4: 1st aux symbol for k+3
k+5: regular sym k+5
k+6: regular sym k+6
The PE format allows for several possible aux symbol formats. For more info
see:
At the moment this package only provides APIs for looking at aux symbols of
format 5 (associated with section definition symbols).
func (sym *COFFSymbol) FullName(st StringTable) (string, error)
FullName finds real name of symbol sym. Normally name is stored in sym.Name,
but if it is longer then 8 characters, it is stored in COFF string table st
instead.
type COFFSymbolAuxFormat5 struct {
Size uint32
NumRelocs uint16
NumLineNumbers uint16
Checksum uint32
SecNum uint16
Selection uint8
}
COFFSymbolAuxFormat5 describes the expected form of an aux symbol
attached to a section definition symbol. The PE format defines
a number of different aux symbol formats: format 1 for function
definitions, format 2 for .be and .ef symbols, and so on. Format 5
holds extra info associated with a section definition, including
number of relocations + line numbers, as well as COMDAT info. See
for more on what's going on here.
type DataDirectory struct {
VirtualAddress uint32
Size uint32
}
func readDataDirectories(r io.ReadSeeker, sz uint16, n uint32) ([]DataDirectory, error)
readDataDirectories accepts an io.ReadSeeker pointing to data directories
in the PE file, its size and number of data directories as seen in optional
header. It parses the given size of bytes and returns given number of data
directories.
type File struct {
FileHeader
Sections []*Section
StringTable StringTable
closer io.Closer
}
A File represents an open PE file.
func NewFile(r io.ReaderAt) (*File, error)
NewFile creates a new File for accessing a PE binary in an underlying
reader.
func Open(name string) (*File, error)
Open opens the named file using os.Open and prepares it for use as a PE
binary.
func (f *File) COFFSymbolReadSectionDefAux(idx int) (*COFFSymbolAuxFormat5, error)
COFFSymbolReadSectionDefAux returns a blob of auxiliary information
(including COMDAT info) for a section definition symbol. Here 'idx' is the
index of a section symbol in the main COFFSymbol array for the File. Return
value is a pointer to the appropriate aux symbol struct. For more info, see:
auxiliary symbols:
COMDAT sections:
auxiliary info for section definitions:
func (f *File) Close() error
Close closes the File. If the File was created using NewFile directly
instead of Open, Close has no effect.
func (f *File) DWARF() (*dwarf.Data, error)
func (f *File) ImportedLibraries() ([]string, error)
ImportedLibraries returns the names of all libraries referred to by the
binary f that are expected to be linked with the binary at dynamic link
time.
func (f *File) ImportedSymbols() ([]string, error)
ImportedSymbols returns the names of all symbols referred to by the binary
f that are expected to be satisfied by other libraries at dynamic load time.
It does not return weak symbols.
func (f *File) Section(name string) *Section
Section returns the first section with the given name, or nil if no such
section exists.
type FileHeader struct {
Machine uint16
NumberOfSections uint16
TimeDateStamp uint32
PointerToSymbolTable uint32
NumberOfSymbols uint32
SizeOfOptionalHeader uint16
Characteristics uint16
}
type FormatError struct {
}
FormatError is unused. The type is retained for compatibility.
func (e *FormatError) Error() string
type ImportDirectory struct {
OriginalFirstThunk uint32
TimeDateStamp uint32
ForwarderChain uint32
Name uint32
FirstThunk uint32
dll string
}
type OptionalHeader32 struct {
Magic uint16
MajorLinkerVersion uint8
MinorLinkerVersion uint8
SizeOfCode uint32
SizeOfInitializedData uint32
SizeOfUninitializedData uint32
AddressOfEntryPoint uint32
BaseOfCode uint32
BaseOfData uint32
ImageBase uint32
SectionAlignment uint32
FileAlignment uint32
MajorOperatingSystemVersion uint16
MinorOperatingSystemVersion uint16
MajorImageVersion uint16
MinorImageVersion uint16
MajorSubsystemVersion uint16
MinorSubsystemVersion uint16
Win32VersionValue uint32
SizeOfImage uint32
SizeOfHeaders uint32
CheckSum uint32
Subsystem uint16
DllCharacteristics uint16
SizeOfStackReserve uint32
SizeOfStackCommit uint32
SizeOfHeapReserve uint32
SizeOfHeapCommit uint32
LoaderFlags uint32
NumberOfRvaAndSizes uint32
DataDirectory [16]DataDirectory
}
type OptionalHeader64 struct {
Magic uint16
MajorLinkerVersion uint8
MinorLinkerVersion uint8
SizeOfCode uint32
SizeOfInitializedData uint32
SizeOfUninitializedData uint32
AddressOfEntryPoint uint32
BaseOfCode uint32
ImageBase uint64
SectionAlignment uint32
FileAlignment uint32
MajorOperatingSystemVersion uint16
MinorOperatingSystemVersion uint16
MajorImageVersion uint16
MinorImageVersion uint16
MajorSubsystemVersion uint16
MinorSubsystemVersion uint16
Win32VersionValue uint32
SizeOfImage uint32
SizeOfHeaders uint32
CheckSum uint32
Subsystem uint16
DllCharacteristics uint16
SizeOfStackReserve uint64
SizeOfStackCommit uint64
SizeOfHeapReserve uint64
SizeOfHeapCommit uint64
LoaderFlags uint32
NumberOfRvaAndSizes uint32
DataDirectory [16]DataDirectory
}
type Reloc struct {
VirtualAddress uint32
SymbolTableIndex uint32
Type uint16
}
Reloc represents a PE COFF relocation. Each section contains its own
relocation list.
func readRelocs(sh *SectionHeader, r io.ReadSeeker) ([]Reloc, error)
type Section struct {
SectionHeader
Relocs []Reloc
io.ReaderAt
sr *io.SectionReader
}
Section provides access to PE COFF section.
func (s *Section) Data() ([]byte, error)
Data reads and returns the contents of the PE section s.
If s.Offset is 0, the section has no contents, and Data will always return a
non-nil error.
func (s *Section) Open() io.ReadSeeker
Open returns a new ReadSeeker reading the PE section s.
If s.Offset is 0, the section has no contents, and all calls to the returned
reader will return a non-nil error.
type SectionHeader struct {
Name string
VirtualSize uint32
VirtualAddress uint32
Size uint32
Offset uint32
PointerToRelocations uint32
PointerToLineNumbers uint32
NumberOfRelocations uint16
NumberOfLineNumbers uint16
Characteristics uint32
}
SectionHeader is similar to SectionHeader32 with Name field replaced by Go
string.
type SectionHeader32 struct {
Name [8]uint8
VirtualSize uint32
VirtualAddress uint32
SizeOfRawData uint32
PointerToRawData uint32
PointerToRelocations uint32
PointerToLineNumbers uint32
NumberOfRelocations uint16
NumberOfLineNumbers uint16
Characteristics uint32
}
SectionHeader32 represents real PE COFF section header.
func (sh *SectionHeader32) fullName(st StringTable) (string, error)
fullName finds real name of section sh. Normally name is stored in sh.Name,
but if it is longer then 8 characters, it is stored in COFF string table st
instead.
type StringTable []byte
StringTable is a COFF string table.
func readStringTable(fh *FileHeader, r io.ReadSeeker) (StringTable, error)
func (st StringTable) String(start uint32) (string, error)
String extracts string from COFF string table st at offset start.
type Symbol struct {
Name string
Value uint32
SectionNumber int16
Type uint16
StorageClass uint8
}
Symbol is similar to COFFSymbol with Name field replaced by Go string.
Symbol also does not have NumberOfAuxSymbols.
func removeAuxSymbols(allsyms []COFFSymbol, st StringTable) ([]*Symbol, error)
type nobitsSectionReader struct{}
func (*nobitsSectionReader) ReadAt(p []byte, off int64) (n int, err error)
debug/plan9obj
func parseMagic(magic []byte) (uint32, error)
func walksymtab(data []byte, ptrsz int, fn func(sym) error) error
TYPES
type File struct {
FileHeader
Sections []*Section
closer io.Closer
}
A File represents an open Plan 9 a.out file.
func NewFile(r io.ReaderAt) (*File, error)
NewFile creates a new File for accessing a Plan 9 binary in an underlying
reader. The Plan 9 binary is expected to start at position 0 in the
ReaderAt.
func Open(name string) (*File, error)
Open opens the named file using os.Open and prepares it for use as a Plan 9
a.out binary.
func (f *File) Close() error
Close closes the File. If the File was created using NewFile directly
instead of Open, Close has no effect.
func (f *File) Section(name string) *Section
Section returns a section with the given name, or nil if no such section
exists.
func (f *File) Symbols() ([]Sym, error)
Symbols returns the symbol table for f.
type FileHeader struct {
Magic uint32
Bss uint32
Entry uint64
PtrSize int
LoadAddress uint64
HdrSize uint64
}
A FileHeader represents a Plan 9 a.out file header.
type Section struct {
SectionHeader
io.ReaderAt
sr *io.SectionReader
}
A Section represents a single section in a Plan 9 a.out file.
func (s *Section) Data() ([]byte, error)
Data reads and returns the contents of the Plan 9 a.out section.
func (s *Section) Open() io.ReadSeeker
Open returns a new ReadSeeker reading the Plan 9 a.out section.
type SectionHeader struct {
Name string
Size uint32
Offset uint32
}
A SectionHeader represents a single Plan 9 a.out section header. This
structure doesn't exist on-disk, but eases navigation through the object
file.
type Sym struct {
Value uint64
Type rune
Name string
}
A Symbol represents an entry in a Plan 9 a.out symbol table section.
func newTable(symtab []byte, ptrsz int) ([]Sym, error)
newTable decodes the Go symbol table in data, returning an in-memory
representation.
type formatError struct {
off int
msg string
val any
}
formatError is returned by some operations if the data does not have the
correct format for an object file.
func (e *formatError) Error() string
type prog struct {
Magic uint32 /* magic number */
Text uint32 /* size of text segment */
Data uint32 /* size of initialized data */
Bss uint32 /* size of uninitialized data */
Syms uint32 /* size of symbol table */
Entry uint32 /* entry point */
Spsz uint32 /* size of pc/sp offset table */
Pcsz uint32 /* size of pc/line number table */
}
Plan 9 Program header.
type sym struct {
value uint64
typ byte
name []byte
}
Plan 9 symbol table entries.
embed
func sortSearch(n int, f func(int) bool) int
sortSearch is like sort.Search, avoiding an import.
func split(name string) (dir, elem string, isDir bool)
split splits the name into dir and elem as described in the comment in the
FS struct above. isDir reports whether the final trailing slash was present,
indicating that name is a directory.
TYPES
type FS struct {
files *[]file
}
An FS is a read-only collection of files, usually initialized with a
an empty file system.
An FS is a read-only value, so it is safe to use from multiple goroutines
simultaneously and also safe to assign values of type FS to each other.
FS implements fs.FS, so it can be used with any package that understands
file system interfaces, including net/http, text/template, and
html/template.
See the package documentation for more details about initializing an FS.
func (f FS) Open(name string) (fs.File, error)
Open opens the named file for reading and returns it as an fs.File.
The returned file implements io.Seeker and io.ReaderAt when the file is not
a directory.
func (f FS) ReadDir(name string) ([]fs.DirEntry, error)
ReadDir reads and returns the entire named directory.
func (f FS) ReadFile(name string) ([]byte, error)
ReadFile reads and returns the content of the named file.
func (f FS) lookup(name string) *file
lookup returns the named file, or nil if it is not present.
func (f FS) readDir(dir string) []file
readDir returns the list of files corresponding to the directory dir.
type file struct {
name string
data string
}
A file is a single file in the FS. It implements fs.FileInfo and
fs.DirEntry.
func (f *file) Info() (fs.FileInfo, error)
func (f *file) IsDir() bool
func (f *file) ModTime() time.Time
func (f *file) Mode() fs.FileMode
func (f *file) Name() string
func (f *file) Size() int64
func (f *file) String() string
func (f *file) Sys() any
func (f *file) Type() fs.FileMode
type openDir struct {
}
An openDir is a directory open for reading.
func (d *openDir) Close() error
func (d *openDir) Read([]byte) (int, error)
func (d *openDir) ReadDir(count int) ([]fs.DirEntry, error)
func (d *openDir) Stat() (fs.FileInfo, error)
type openFile struct {
}
An openFile is a regular file open for reading.
func (f *openFile) Close() error
func (f *openFile) Read(b []byte) (int, error)
func (f *openFile) ReadAt(b []byte, offset int64) (int, error)
func (f *openFile) Seek(offset int64, whence int) (int64, error)
func (f *openFile) Stat() (fs.FileInfo, error)
embed/internal/embedtest
encoding
encoding/ascii85
func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err error)
Decode decodes src into dst, returning both the number of bytes written to
dst and the number consumed from src. If src contains invalid ascii85 data,
Decode will return the number of bytes successfully written and a
CorruptInputError. Decode ignores space and control characters in src.
Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Decode expects
these to have been stripped by the caller.
If flush is true, Decode assumes that src represents the end of the input
stream and processes it completely rather than wait for the completion of
another 32-bit block.
NewDecoder wraps an io.Reader interface around Decode.
func Encode(dst, src []byte) int
Encode encodes src into at most MaxEncodedLen(len(src)) bytes of dst,
returning the actual number of bytes written.
The encoding handles 4-byte chunks, using a special encoding for the last
fragment, so Encode is not appropriate for use on individual blocks of a
large data stream. Use NewEncoder instead.
Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Encode does not
add these.
func MaxEncodedLen(n int) int
MaxEncodedLen returns the maximum length of an encoding of n source bytes.
func NewDecoder(r io.Reader) io.Reader
NewDecoder constructs a new ascii85 stream decoder.
func NewEncoder(w io.Writer) io.WriteCloser
NewEncoder returns a new ascii85 stream encoder. Data written to the
returned writer will be encoded and then written to w. Ascii85 encodings
operate in 32-bit blocks; when finished writing, the caller must Close the
returned encoder to flush any trailing partial block.
TYPES
type CorruptInputError int64
func (e CorruptInputError) Error() string
type decoder struct {
err error
readErr error
r io.Reader
nbuf int
outbuf [1024]byte
}
func (d *decoder) Read(p []byte) (n int, err error)
type encoder struct {
err error
w io.Writer
}
func (e *encoder) Close() error
Close flushes any pending output from the encoder. It is an error to call
Write after calling Close.
func (e *encoder) Write(p []byte) (n int, err error)
encoding/asn1
func Marshal(val any) ([]byte, error)
Marshal returns the ASN.1 encoding of val.
In addition to the struct tags recognized by Unmarshal, the following can be
used:
ia5: causes strings to be marshaled as ASN.1, IA5String values
omitempty: causes empty slices to be skipped
printable: causes strings to be marshaled as ASN.1, PrintableString values
utf8: causes strings to be marshaled as ASN.1, UTF8String values
utc: causes time.Time to be marshaled as ASN.1, UTCTime values
generalized: causes time.Time to be marshaled as ASN.1, GeneralizedTime values
func MarshalWithParams(val any, params string) ([]byte, error)
MarshalWithParams allows field parameters to be specified for the top-level
element. The form of the params is the same as the field tags.
func Unmarshal(b []byte, val any) (rest []byte, err error)
Unmarshal parses the DER-encoded ASN.1 data structure b and uses the reflect
package to fill in an arbitrary value pointed at by val. Because Unmarshal
uses the reflect package, the structs being written to must use upper case
field names. If val is nil or not a pointer, Unmarshal returns an error.
After parsing b, any bytes that were leftover and not used to fill val will
be returned in rest. When parsing a SEQUENCE into a struct, any trailing
elements of the SEQUENCE that do not have matching fields in val will not be
included in rest, as these are considered valid elements of the SEQUENCE and
not trailing data.
- An ASN.1 INTEGER can be written to an int, int32, int64, or *big.Int.
If the encoded value does not fit in the Go type, Unmarshal returns a
parse error.
- An ASN.1 BIT STRING can be written to a BitString.
- An ASN.1 OCTET STRING can be written to a []byte.
- An ASN.1 OBJECT IDENTIFIER can be written to an ObjectIdentifier.
- An ASN.1 ENUMERATED can be written to an Enumerated.
- An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.
- An ASN.1 PrintableString, IA5String, or NumericString can be written to
a string.
- Any of the above ASN.1 values can be written to an interface{}.
The value stored in the interface has the corresponding Go type.
For integers, that type is int64.
- An ASN.1 SEQUENCE OF x or SET OF x can be written to a slice if an x can
be written to the slice's element type.
- An ASN.1 SEQUENCE or SET can be written to a struct if each of the
elements in the sequence can be written to the corresponding element in
the struct.
The following tags on struct fields have special meaning to Unmarshal:
application specifies that an APPLICATION tag is used
private specifies that a PRIVATE tag is used
default:x sets the default value for optional integer fields (only used if optional is also present)
explicit specifies that an additional, explicit tag wraps the implicit one
optional marks the field as ASN.1 OPTIONAL
set causes a SET, rather than a SEQUENCE type to be expected
tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
When decoding an ASN.1 value with an IMPLICIT tag into a string field,
Unmarshal will default to a PrintableString, which doesn't support
characters such as '@' and '&'. To force other encodings, use the following
tags:
ia5 causes strings to be unmarshaled as ASN.1 IA5String values
numeric causes strings to be unmarshaled as ASN.1 NumericString values
utf8 causes strings to be unmarshaled as ASN.1 UTF8String values
If the type of the first field of a structure is RawContent then the raw
ASN1 contents of the struct will be stored in it.
If the name of a slice type ends with "SET" then it's treated as if the
"set" tag was set on it. This results in interpreting the type as a SET OF
x rather than a SEQUENCE OF x. This can be used with nested slices where a
struct tag cannot be given.
Other ASN.1 types are not supported; if it encounters them, Unmarshal
returns a parse error.
func UnmarshalWithParams(b []byte, val any, params string) (rest []byte, err error)
UnmarshalWithParams allows field parameters to be specified for the
top-level element. The form of the params is the same as the field tags.
func appendBase128Int(dst []byte, n int64) []byte
func appendFourDigits(dst []byte, v int) []byte
func appendGeneralizedTime(dst []byte, t time.Time) (ret []byte, err error)
func appendLength(dst []byte, i int) []byte
func appendTagAndLength(dst []byte, t tagAndLength) []byte
func appendTimeCommon(dst []byte, t time.Time) []byte
func appendTwoDigits(dst []byte, v int) []byte
func appendUTCTime(dst []byte, t time.Time) (ret []byte, err error)
func base128IntLength(n int64) int
func canHaveDefaultValue(k reflect.Kind) bool
canHaveDefaultValue reports whether k is a Kind that we will set a default
value for. (A signed integer, essentially.)
func checkInteger(bytes []byte) error
checkInteger returns nil if the given bytes are a valid DER-encoded INTEGER
and an error otherwise.
func getUniversalType(t reflect.Type) (matchAny bool, tagNumber int, isCompound, ok bool)
Given a reflected Go type, getUniversalType returns the default tag number
and expected compound flag.
func invalidLength(offset, length, sliceLength int) bool
invalidLength reports whether offset + length > sliceLength, or if the
addition would overflow.
func isNumeric(b byte) bool
isNumeric reports whether the given b is in the ASN.1 NumericString set.
func isPrintable(b byte, asterisk asteriskFlag, ampersand ampersandFlag) bool
isPrintable reports whether the given b is in the ASN.1 PrintableString set.
If asterisk is allowAsterisk then '*' is also allowed, reflecting existing
practice. If ampersand is allowAmpersand then '&' is allowed as well.
func lengthLength(i int) (numBytes int)
func outsideUTCRange(t time.Time) bool
func parseBMPString(bmpString []byte) (string, error)
parseBMPString parses an ASN.1 BMPString (Basic Multilingual Plane of
ISO/IEC/ITU 10646-1) from the given byte slice and returns it.
func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error)
parseBase128Int parses a base-128 encoded int from the given offset in the
given byte slice. It returns the value and the new offset.
func parseBigInt(bytes []byte) (*big.Int, error)
parseBigInt treats the given bytes as a big-endian, signed integer and
returns the result.
func parseBool(bytes []byte) (ret bool, err error)
func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error)
parseField is the main parsing function. Given a byte slice and an offset
into the array, it will try to parse a suitable ASN.1 value out and store it
in the given Value.
func parseGeneralizedTime(bytes []byte) (ret time.Time, err error)
parseGeneralizedTime parses the GeneralizedTime from the given byte slice
and returns the resulting time.
func parseIA5String(bytes []byte) (ret string, err error)
parseIA5String parses an ASN.1 IA5String (ASCII string) from the given byte
slice and returns it.
func parseInt32(bytes []byte) (int32, error)
parseInt32 treats the given bytes as a big-endian, signed integer and
returns the result.
func parseInt64(bytes []byte) (ret int64, err error)
parseInt64 treats the given bytes as a big-endian, signed integer and
returns the result.
func parseNumericString(bytes []byte) (ret string, err error)
parseNumericString parses an ASN.1 NumericString from the given byte array
and returns it.
func parsePrintableString(bytes []byte) (ret string, err error)
parsePrintableString parses an ASN.1 PrintableString from the given byte
array and returns it.
func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error)
parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse
a number of ASN.1 values from the given byte slice and returns them as a
slice of Go values of the given type.
func parseT61String(bytes []byte) (ret string, err error)
parseT61String parses an ASN.1 T61String (8-bit clean string) from the given
byte slice and returns it.
func parseUTCTime(bytes []byte) (ret time.Time, err error)
func parseUTF8String(bytes []byte) (ret string, err error)
parseUTF8String parses an ASN.1 UTF8String (raw UTF-8) from the given byte
array and returns it.
func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool)
setDefaultValue is used to install a default value, from a tag string,
into a Value. It is successful if the field was optional, even if a default
value wasn't provided or it failed to install it into the Value.
func stripTagAndLength(in []byte) []byte
TYPES
type BitString struct {
}
BitString is the structure to use when you want an ASN.1 BIT STRING type.
A bit string is padded up to the nearest byte in memory and the number of
valid bits is recorded. Padding bits will be zero.
func parseBitString(bytes []byte) (ret BitString, err error)
parseBitString parses an ASN.1 bit string from the given byte slice and
returns it.
func (b BitString) At(i int) int
At returns the bit at the given index. If the index is out of range it
returns 0.
func (b BitString) RightAlign() []byte
RightAlign returns a slice where the padding bits are at the beginning.
The slice may share memory with the BitString.
type Enumerated int
An Enumerated is represented as a plain int.
type Flag bool
A Flag accepts any data and is set to true if present.
type ObjectIdentifier []int
An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.
func parseObjectIdentifier(bytes []byte) (s ObjectIdentifier, err error)
parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
returns it. An object identifier is a sequence of variable length integers
that are assigned in a hierarchy.
func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool
Equal reports whether oi and other represent the same identifier.
func (oi ObjectIdentifier) String() string
type RawContent []byte
RawContent is used to signal that the undecoded, DER data needs to be
preserved for a struct. To use it, the first field of the struct must have
this type. It's an error for any of the other fields to have this type.
type RawValue struct {
Class, Tag int
IsCompound bool
Bytes []byte
}
A RawValue represents an undecoded ASN.1 object.
type StructuralError struct {
Msg string
}
A StructuralError suggests that the ASN.1 data is valid, but the Go type
which is receiving it doesn't match.
func (e StructuralError) Error() string
type SyntaxError struct {
Msg string
}
A SyntaxError suggests that the ASN.1 data is invalid.
func (e SyntaxError) Error() string
type ampersandFlag bool
type asteriskFlag bool
type bitStringEncoder BitString
func (b bitStringEncoder) Encode(dst []byte)
func (b bitStringEncoder) Len() int
type byteEncoder byte
func (c byteEncoder) Encode(dst []byte)
func (c byteEncoder) Len() int
type bytesEncoder []byte
func (b bytesEncoder) Encode(dst []byte)
func (b bytesEncoder) Len() int
type encoder interface {
Len() int
Encode(dst []byte)
}
encoder represents an ASN.1 element that is waiting to be marshaled.
var (
byte00Encoder encoder = byteEncoder(0x00)
byteFFEncoder encoder = byteEncoder(0xff)
)
func makeBigInt(n *big.Int) (encoder, error)
func makeBody(value reflect.Value, params fieldParameters) (e encoder, err error)
func makeField(v reflect.Value, params fieldParameters) (e encoder, err error)
func makeGeneralizedTime(t time.Time) (e encoder, err error)
func makeIA5String(s string) (e encoder, err error)
func makeNumericString(s string) (e encoder, err error)
func makeObjectIdentifier(oid []int) (e encoder, err error)
func makePrintableString(s string) (e encoder, err error)
func makeUTCTime(t time.Time) (e encoder, err error)
func makeUTF8String(s string) encoder
type fieldParameters struct {
}
fieldParameters is the parsed representation of tag string from a structure
field.
func parseFieldParameters(str string) (ret fieldParameters)
Given a tag string with the format specified in the package comment,
parseFieldParameters will parse it into a fieldParameters structure,
ignoring unknown parts of the string.
type int64Encoder int64
func (i int64Encoder) Encode(dst []byte)
func (i int64Encoder) Len() int
type invalidUnmarshalError struct {
Type reflect.Type
}
An invalidUnmarshalError describes an invalid argument passed to Unmarshal.
(The argument to Unmarshal must be a non-nil pointer.)
func (e *invalidUnmarshalError) Error() string
type multiEncoder []encoder
func (m multiEncoder) Encode(dst []byte)
func (m multiEncoder) Len() int
type oidEncoder []int
func (oid oidEncoder) Encode(dst []byte)
func (oid oidEncoder) Len() int
type setEncoder []encoder
func (s setEncoder) Encode(dst []byte)
func (s setEncoder) Len() int
type stringEncoder string
func (s stringEncoder) Encode(dst []byte)
func (s stringEncoder) Len() int
type tagAndLength struct {
class, tag, length int
isCompound bool
}
func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error)
parseTagAndLength parses an ASN.1 tag and length pair from the given offset
into a byte slice. It returns the parsed data and the new offset. SET and
SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we
don't distinguish between ordered and unordered objects in this code.
type taggedEncoder struct {
scratch [8]byte
tag encoder
body encoder
}
func (t *taggedEncoder) Encode(dst []byte)
func (t *taggedEncoder) Len() int
encoding/base32
func NewDecoder(enc *Encoding, r io.Reader) io.Reader
NewDecoder constructs a new base32 stream decoder.
func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser
NewEncoder returns a new base32 stream encoder. Data written to the returned
writer will be encoded using enc and then written to w. Base32 encodings
operate in 5-byte blocks; when finished writing, the caller must Close the
returned encoder to flush any partially written blocks.
func decodedLen(n int, padChar rune) int
func readEncodedData(r io.Reader, buf []byte, min int, expectsPadding bool) (n int, err error)
func stripNewlines(dst, src []byte) int
stripNewlines removes newline characters and returns the number of
non-newline characters copied to dst.
TYPES
type CorruptInputError int64
func (e CorruptInputError) Error() string
type Encoding struct {
padChar rune
}
An Encoding is a radix 32 encoding/decoding scheme, defined by a
32-character alphabet. The most common is the "base32" encoding introduced
for SASL GSSAPI and standardized in RFC 4648. The alternate "base32hex"
encoding is used in DNSSEC.
func NewEncoding(encoder string) *Encoding
NewEncoding returns a new padded Encoding defined by the given alphabet,
which must be a 32-byte string that contains unique byte values and does
not contain the padding character or CR / LF ('\r', '\n'). The alphabet
is treated as a sequence of byte values without any special treatment for
multi-byte UTF-8. The resulting Encoding uses the default padding character
('='), which may be changed or disabled via Encoding.WithPadding.
func (enc *Encoding) AppendDecode(dst, src []byte) ([]byte, error)
AppendDecode appends the base32 decoded src to dst and returns the extended
buffer. If the input is malformed, it returns the partially decoded src and
an error. New line characters (\r and \n) are ignored.
func (enc *Encoding) AppendEncode(dst, src []byte) []byte
AppendEncode appends the base32 encoded src to dst and returns the extended
buffer.
func (enc *Encoding) Decode(dst, src []byte) (n int, err error)
Decode decodes src using the encoding enc. It writes at most
Encoding.DecodedLen(len(src)) bytes to dst and returns the number of bytes
written. The caller must ensure that dst is large enough to hold all the
decoded data. If src contains invalid base32 data, it will return the number
of bytes successfully written and CorruptInputError. Newline characters (\r
and \n) are ignored.
func (enc *Encoding) DecodeString(s string) ([]byte, error)
DecodeString returns the bytes represented by the base32 string s.
If the input is malformed, it returns the partially decoded data and
CorruptInputError. New line characters (\r and \n) are ignored.
func (enc *Encoding) DecodedLen(n int) int
DecodedLen returns the maximum length in bytes of the decoded data
corresponding to n bytes of base32-encoded data.
func (enc *Encoding) Encode(dst, src []byte)
Encode encodes src using the encoding enc, writing
Encoding.EncodedLen(len(src)) bytes to dst.
The encoding pads the output to a multiple of 8 bytes, so Encode is
not appropriate for use on individual blocks of a large data stream.
Use NewEncoder instead.
func (enc *Encoding) EncodeToString(src []byte) string
EncodeToString returns the base32 encoding of src.
func (enc *Encoding) EncodedLen(n int) int
EncodedLen returns the length in bytes of the base32 encoding of an input
buffer of length n.
func (enc Encoding) WithPadding(padding rune) *Encoding
WithPadding creates a new encoding identical to enc except with a specified
padding character, or NoPadding to disable padding. The padding character
must not be '\r' or '\n', must not be contained in the encoding's alphabet,
must not be negative, and must be a rune equal or below '\xff'. Padding
characters above '\x7f' are encoded as their exact byte value rather than
using the UTF-8 representation of the codepoint.
func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error)
decode is like Decode but returns an additional 'end' value, which indicates
if end-of-message padding was encountered and thus any additional data is
an error. This method assumes that src has been stripped of all supported
whitespace ('\r' and '\n').
type decoder struct {
err error
enc *Encoding
r io.Reader
nbuf int
outbuf [1024 / 8 * 5]byte
}
func (d *decoder) Read(p []byte) (n int, err error)
type encoder struct {
err error
enc *Encoding
w io.Writer
}
func (e *encoder) Close() error
Close flushes any pending output from the encoder. It is an error to call
Write after calling Close.
func (e *encoder) Write(p []byte) (n int, err error)
type newlineFilteringReader struct {
wrapped io.Reader
}
func (r *newlineFilteringReader) Read(p []byte) (int, error)
encoding/base64
func NewDecoder(enc *Encoding, r io.Reader) io.Reader
NewDecoder constructs a new base64 stream decoder.
func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser
NewEncoder returns a new base64 stream encoder. Data written to the returned
writer will be encoded using enc and then written to w. Base64 encodings
operate in 4-byte blocks; when finished writing, the caller must Close the
returned encoder to flush any partially written blocks.
func assemble32(n1, n2, n3, n4 byte) (dn uint32, ok bool)
assemble32 assembles 4 base64 digits into 3 bytes. Each digit comes from the
decode map, and will be 0xff if it came from an invalid character.
func assemble64(n1, n2, n3, n4, n5, n6, n7, n8 byte) (dn uint64, ok bool)
assemble64 assembles 8 base64 digits into 6 bytes. Each digit comes from the
decode map, and will be 0xff if it came from an invalid character.
func decodedLen(n int, padChar rune) int
TYPES
type CorruptInputError int64
func (e CorruptInputError) Error() string
type Encoding struct {
padChar rune
strict bool
}
An Encoding is a radix 64 encoding/decoding scheme, defined by a
64-character alphabet. The most common encoding is the "base64" encoding
defined in RFC 4648 and used in MIME (RFC 2045) and PEM (RFC 1421). RFC 4648
also defines an alternate encoding, which is the standard encoding with -
and _ substituted for + and /.
func NewEncoding(encoder string) *Encoding
NewEncoding returns a new padded Encoding defined by the given alphabet,
which must be a 64-byte string that contains unique byte values and does
not contain the padding character or CR / LF ('\r', '\n'). The alphabet
is treated as a sequence of byte values without any special treatment for
multi-byte UTF-8. The resulting Encoding uses the default padding character
('='), which may be changed or disabled via Encoding.WithPadding.
func (enc *Encoding) AppendDecode(dst, src []byte) ([]byte, error)
AppendDecode appends the base64 decoded src to dst and returns the extended
buffer. If the input is malformed, it returns the partially decoded src and
an error. New line characters (\r and \n) are ignored.
func (enc *Encoding) AppendEncode(dst, src []byte) []byte
AppendEncode appends the base64 encoded src to dst and returns the extended
buffer.
func (enc *Encoding) Decode(dst, src []byte) (n int, err error)
Decode decodes src using the encoding enc. It writes at most
Encoding.DecodedLen(len(src)) bytes to dst and returns the number of bytes
written. The caller must ensure that dst is large enough to hold all the
decoded data. If src contains invalid base64 data, it will return the number
of bytes successfully written and CorruptInputError. New line characters (\r
and \n) are ignored.
func (enc *Encoding) DecodeString(s string) ([]byte, error)
DecodeString returns the bytes represented by the base64 string s.
If the input is malformed, it returns the partially decoded data and
CorruptInputError. New line characters (\r and \n) are ignored.
func (enc *Encoding) DecodedLen(n int) int
DecodedLen returns the maximum length in bytes of the decoded data
corresponding to n bytes of base64-encoded data.
func (enc *Encoding) Encode(dst, src []byte)
Encode encodes src using the encoding enc, writing
Encoding.EncodedLen(len(src)) bytes to dst.
The encoding pads the output to a multiple of 4 bytes, so Encode is
not appropriate for use on individual blocks of a large data stream.
Use NewEncoder instead.
func (enc *Encoding) EncodeToString(src []byte) string
EncodeToString returns the base64 encoding of src.
func (enc *Encoding) EncodedLen(n int) int
EncodedLen returns the length in bytes of the base64 encoding of an input
buffer of length n.
func (enc Encoding) Strict() *Encoding
Strict creates a new encoding identical to enc except with strict decoding
enabled. In this mode, the decoder requires that trailing padding bits are
zero, as described in RFC 4648 section 3.5.
Note that the input is still malleable, as new line characters (CR and LF)
are still ignored.
func (enc Encoding) WithPadding(padding rune) *Encoding
WithPadding creates a new encoding identical to enc except with a specified
padding character, or NoPadding to disable padding. The padding character
must not be '\r' or '\n', must not be contained in the encoding's alphabet,
must not be negative, and must be a rune equal or below '\xff'. Padding
characters above '\x7f' are encoded as their exact byte value rather than
using the UTF-8 representation of the codepoint.
func (enc *Encoding) decodeQuantum(dst, src []byte, si int) (nsi, n int, err error)
decodeQuantum decodes up to 4 base64 bytes. The received parameters are the
destination buffer dst, the source buffer src and an index in the source
buffer si. It returns the number of bytes read from src, the number of bytes
written to dst, and an error, if any.
type decoder struct {
err error
enc *Encoding
r io.Reader
nbuf int
outbuf [1024 / 4 * 3]byte
}
func (d *decoder) Read(p []byte) (n int, err error)
type encoder struct {
err error
enc *Encoding
w io.Writer
}
func (e *encoder) Close() error
Close flushes any pending output from the encoder. It is an error to call
Write after calling Close.
func (e *encoder) Write(p []byte) (n int, err error)
type newlineFilteringReader struct {
wrapped io.Reader
}
func (r *newlineFilteringReader) Read(p []byte) (int, error)
encoding/binary
func Append(buf []byte, order ByteOrder, data any) ([]byte, error)
Append appends the binary representation of data to buf. buf may be nil,
in which case a new buffer will be allocated. See Write on which data are
acceptable. It returns the (possibly extended) buffer containing data or an
error.
func AppendUvarint(buf []byte, x uint64) []byte
AppendUvarint appends the varint-encoded form of x, as generated by
PutUvarint, to buf and returns the extended buffer.
func AppendVarint(buf []byte, x int64) []byte
AppendVarint appends the varint-encoded form of x, as generated by
PutVarint, to buf and returns the extended buffer.
func Decode(buf []byte, order ByteOrder, data any) (int, error)
Decode decodes binary data from buf into data according to the given byte
order. It returns an error if buf is too small, otherwise the number of
bytes consumed from buf.
func Encode(buf []byte, order ByteOrder, data any) (int, error)
Encode encodes the binary representation of data into buf according to the
given byte order. It returns an error if buf is too small, otherwise the
number of bytes written into buf.
func PutUvarint(buf []byte, x uint64) int
PutUvarint encodes a uint64 into buf and returns the number of bytes
written. If the buffer is too small, PutUvarint will panic.
func PutVarint(buf []byte, x int64) int
PutVarint encodes an int64 into buf and returns the number of bytes written.
If the buffer is too small, PutVarint will panic.
func Read(r io.Reader, order ByteOrder, data any) error
Read reads structured binary data from r into data. Data must be a pointer
to a fixed-size value or a slice of fixed-size values. Bytes read from r
are decoded using the specified byte order and written to successive fields
of the data. When decoding boolean values, a zero byte is decoded as false,
and any other non-zero byte is decoded as true. When reading into structs,
the field data for fields with blank (_) field names is skipped; i.e.,
blank field names may be used for padding. When reading into a struct,
all non-blank fields must be exported or Read may panic.
The error is io.EOF only if no bytes were read. If an io.EOF happens after
reading some but not all the bytes, Read returns io.ErrUnexpectedEOF.
func ReadUvarint(r io.ByteReader) (uint64, error)
ReadUvarint reads an encoded unsigned integer from r and returns it as
a uint64. The error is io.EOF only if no bytes were read. If an io.EOF
happens after reading some but not all the bytes, ReadUvarint returns
io.ErrUnexpectedEOF.
func ReadVarint(r io.ByteReader) (int64, error)
ReadVarint reads an encoded signed integer from r and returns it as an
int64. The error is io.EOF only if no bytes were read. If an io.EOF
happens after reading some but not all the bytes, ReadVarint returns
io.ErrUnexpectedEOF.
func Size(v any) int
Size returns how many bytes Write would generate to encode the value v,
which must be a fixed-size value or a slice of fixed-size values, or a
pointer to such data. If v is neither of these, Size returns -1.
func Uvarint(buf []byte) (uint64, int)
Uvarint decodes a uint64 from buf and returns that value and the number of
bytes read (> 0). If an error occurred, the value is 0 and the number of
bytes n is <= 0 meaning:
- n == 0: buf too small;
- n < 0: value larger than 64 bits (overflow) and -n is the number of
bytes read.
func Varint(buf []byte) (int64, int)
Varint decodes an int64 from buf and returns that value and the number of
bytes read (> 0). If an error occurred, the value is 0 and the number of
bytes n is <= 0 with the following meaning:
- n == 0: buf too small;
- n < 0: value larger than 64 bits (overflow) and -n is the number of
bytes read.
func Write(w io.Writer, order ByteOrder, data any) error
Write writes the binary representation of data into w. Data must be a
fixed-size value or a slice of fixed-size values, or a pointer to such
data. Boolean values encode as one byte: 1 for true, and 0 for false.
Bytes written to w are encoded using the specified byte order and read from
successive fields of the data. When writing structs, zero values are written
for fields with blank (_) field names.
func dataSize(v reflect.Value) int
dataSize returns the number of bytes the actual data represented by v
occupies in memory. For compound structures, it sums the sizes of the
elements. Thus, for instance, for a slice it returns the length of the slice
times the element size and does not count the memory occupied by the header.
If the type of v is not acceptable, dataSize returns -1.
func decodeFast(bs []byte, order ByteOrder, data any) bool
func encodeFast(bs []byte, order ByteOrder, data any)
func ensure(buf []byte, n int) (buf2, pos []byte)
ensure grows buf to length len(buf) + n and returns the grown buffer and a
slice starting at the original length of buf (that is, buf2[len(buf):]).
func intDataSize(data any) (int, []byte)
intDataSize returns the size of the data required to represent the data
when encoded, and optionally a byte slice containing the encoded data if
no conversion is necessary. It returns zero, nil if the type cannot be
implemented by the fast path in Read or Write.
func sizeof(t reflect.Type) int
sizeof returns the size >= 0 of variables for the given type or -1 if the
type is not acceptable.
TYPES
type AppendByteOrder interface {
AppendUint16([]byte, uint16) []byte
AppendUint32([]byte, uint32) []byte
AppendUint64([]byte, uint64) []byte
String() string
}
AppendByteOrder specifies how to append 16-, 32-, or 64-bit unsigned
integers into a byte slice.
It is implemented by LittleEndian, BigEndian, and NativeEndian.
type ByteOrder interface {
Uint16([]byte) uint16
Uint32([]byte) uint32
Uint64([]byte) uint64
PutUint16([]byte, uint16)
PutUint32([]byte, uint32)
PutUint64([]byte, uint64)
String() string
}
A ByteOrder specifies how to convert byte slices into 16-, 32-, or 64-bit
unsigned integers.
It is implemented by LittleEndian, BigEndian, and NativeEndian.
type bigEndian struct{}
var BigEndian bigEndian
BigEndian is the big-endian implementation of ByteOrder and AppendByteOrder.
func (bigEndian) AppendUint16(b []byte, v uint16) []byte
func (bigEndian) AppendUint32(b []byte, v uint32) []byte
func (bigEndian) AppendUint64(b []byte, v uint64) []byte
func (bigEndian) GoString() string
func (bigEndian) PutUint16(b []byte, v uint16)
func (bigEndian) PutUint32(b []byte, v uint32)
func (bigEndian) PutUint64(b []byte, v uint64)
func (bigEndian) String() string
func (bigEndian) Uint16(b []byte) uint16
func (bigEndian) Uint32(b []byte) uint32
func (bigEndian) Uint64(b []byte) uint64
type coder struct {
order ByteOrder
buf []byte
offset int
}
type decoder coder
func (d *decoder) bool() bool
func (d *decoder) int16() int16
func (d *decoder) int32() int32
func (d *decoder) int64() int64
func (d *decoder) int8() int8
func (d *decoder) skip(v reflect.Value)
func (d *decoder) uint16() uint16
func (d *decoder) uint32() uint32
func (d *decoder) uint64() uint64
func (d *decoder) uint8() uint8
func (d *decoder) value(v reflect.Value)
type encoder coder
func (e *encoder) bool(x bool)
func (e *encoder) int16(x int16)
func (e *encoder) int32(x int32)
func (e *encoder) int64(x int64)
func (e *encoder) int8(x int8)
func (e *encoder) skip(v reflect.Value)
func (e *encoder) uint16(x uint16)
func (e *encoder) uint32(x uint32)
func (e *encoder) uint64(x uint64)
func (e *encoder) uint8(x uint8)
func (e *encoder) value(v reflect.Value)
type littleEndian struct{}
var LittleEndian littleEndian
LittleEndian is the little-endian implementation of ByteOrder and
AppendByteOrder.
func (littleEndian) AppendUint16(b []byte, v uint16) []byte
func (littleEndian) AppendUint32(b []byte, v uint32) []byte
func (littleEndian) AppendUint64(b []byte, v uint64) []byte
func (littleEndian) GoString() string
func (littleEndian) PutUint16(b []byte, v uint16)
func (littleEndian) PutUint32(b []byte, v uint32)
func (littleEndian) PutUint64(b []byte, v uint64)
func (littleEndian) String() string
func (littleEndian) Uint16(b []byte) uint16
func (littleEndian) Uint32(b []byte) uint32
func (littleEndian) Uint64(b []byte) uint64
type nativeEndian struct {
littleEndian
}
var NativeEndian nativeEndian
NativeEndian is the native-endian implementation of ByteOrder and
AppendByteOrder.
func (nativeEndian) AppendUint16(b []byte, v uint16) []byte
func (nativeEndian) AppendUint32(b []byte, v uint32) []byte
func (nativeEndian) AppendUint64(b []byte, v uint64) []byte
func (nativeEndian) GoString() string
func (nativeEndian) PutUint16(b []byte, v uint16)
func (nativeEndian) PutUint32(b []byte, v uint32)
func (nativeEndian) PutUint64(b []byte, v uint64)
func (nativeEndian) String() string
func (nativeEndian) Uint16(b []byte) uint16
func (nativeEndian) Uint32(b []byte) uint32
func (nativeEndian) Uint64(b []byte) uint64
encoding/csv
func lengthNL(b []byte) int
lengthNL reports the number of bytes for the trailing \n.
func nextRune(b []byte) rune
nextRune returns the next rune in b or utf8.RuneError.
func validDelim(r rune) bool
TYPES
type ParseError struct {
}
A ParseError is returned for parsing errors. Line and column numbers are
1-indexed.
func (e *ParseError) Error() string
func (e *ParseError) Unwrap() error
type Reader struct {
Comma rune
Comment rune
FieldsPerRecord int
LazyQuotes bool
TrimLeadingSpace bool
ReuseRecord bool
TrailingComma bool
r *bufio.Reader
numLine int
offset int64
rawBuffer []byte
recordBuffer []byte
fieldIndexes []int
fieldPositions []position
lastRecord []string
}
A Reader reads records from a CSV-encoded file.
As returned by NewReader, a Reader expects input conforming to RFC 4180.
The exported fields can be changed to customize the details before the first
call to Reader.Read or Reader.ReadAll.
The Reader converts all \r\n sequences in its input to plain \n, including
in multiline field values, so that the returned data does not depend on
which line-ending convention an input file uses.
func NewReader(r io.Reader) *Reader
NewReader returns a new Reader that reads from r.
func (r *Reader) FieldPos(field int) (line, column int)
FieldPos returns the line and column corresponding to the start of the field
with the given index in the slice most recently returned by Reader.Read.
Numbering of lines and columns starts at 1; columns are counted in bytes,
not runes.
If this is called with an out-of-bounds index, it panics.
func (r *Reader) InputOffset() int64
InputOffset returns the input stream byte offset of the current reader
position. The offset gives the location of the end of the most recently read
row and the beginning of the next row.
func (r *Reader) Read() (record []string, err error)
Read reads one record (a slice of fields) from r. If the record has an
unexpected number of fields, Read returns the record along with the error
ErrFieldCount. If the record contains a field that cannot be parsed,
Read returns a partial record along with the parse error. The partial
record contains all fields read before the error. If there is no data left
to be read, Read returns nil, io.EOF. If [Reader.ReuseRecord] is true,
the returned slice may be shared between multiple calls to Read.
func (r *Reader) ReadAll() (records [][]string, err error)
ReadAll reads all the remaining records from r. Each record is a slice of
fields. A successful call returns err == nil, not err == io.EOF. Because
ReadAll is defined to read until EOF, it does not treat end of file as an
error to be reported.
func (r *Reader) readLine() ([]byte, error)
readLine reads the next line (with the trailing endline). If EOF is hit
without a trailing endline, it will be omitted. If some bytes were read,
then the error is never io.EOF. The result is only valid until the next call
to readLine.
func (r *Reader) readRecord(dst []string) ([]string, error)
type Writer struct {
w *bufio.Writer
}
A Writer writes records using CSV encoding.
As returned by NewWriter, a Writer writes records terminated by a
newline and uses ',' as the field delimiter. The exported fields can be
changed to customize the details before the first call to Writer.Write or
Writer.WriteAll.
[Writer.Comma] is the field delimiter.
If [Writer.UseCRLF] is true, the Writer ends each output line with \r\n
instead of \n.
The writes of individual records are buffered. After all data has been
written, the client should call the Writer.Flush method to guarantee
all data has been forwarded to the underlying io.Writer. Any errors that
occurred should be checked by calling the Writer.Error method.
func NewWriter(w io.Writer) *Writer
NewWriter returns a new Writer that writes to w.
func (w *Writer) Error() error
Error reports any error that has occurred during a previous Writer.Write or
Writer.Flush.
func (w *Writer) Flush()
Flush writes any buffered data to the underlying io.Writer. To check if an
error occurred during Flush, call Writer.Error.
func (w *Writer) Write(record []string) error
Write writes a single CSV record to w along with any necessary quoting.
A record is a slice of strings with each string being one field. Writes
are buffered, so Writer.Flush must eventually be called to ensure that the
record is written to the underlying io.Writer.
func (w *Writer) WriteAll(records [][]string) error
WriteAll writes multiple CSV records to w using Writer.Write and then calls
Writer.Flush, returning any error from the Flush.
func (w *Writer) fieldNeedsQuotes(field string) bool
fieldNeedsQuotes reports whether our field must be enclosed in quotes.
Fields with a Comma, fields with a quote or newline, and fields which start
with a space must be enclosed in quotes. We used to quote empty strings,
but we do not anymore (as of Go 1.4). The two representations should be
equivalent, but Postgres distinguishes quoted vs non-quoted empty string
during database imports, and it has an option to force the quoted behavior
for non-quoted CSV but it has no option to force the non-quoted behavior
for quoted CSV, making CSV with quoted empty strings strictly less useful.
Not quoting the empty string also makes this package match the behavior of
Microsoft Excel and Google Drive. For Postgres, quote the data terminating
string `\.`.
type position struct {
line, col int
}
pos holds the position of a field in the current line.
encoding/gob
func Register(value any)
Register records a type, identified by a value for that type, under
its internal type name. That name will identify the concrete type of a
value sent or received as an interface variable. Only types that will be
transferred as implementations of interface values need to be registered.
Expecting to be used only during initialization, it panics if the mapping
between types and names is not a bijection.
func RegisterName(name string, value any)
RegisterName is like Register but uses the provided name rather than the
type's default.
func allocValue(t reflect.Type) reflect.Value
Gob depends on being able to take the address of zeroed Values it creates,
so use this wrapper instead of the standard reflect.Zero. Each call
allocates once.
func catchError(err *error)
catchError is meant to be used as a deferred function to turn a
panic(gobError) into a plain error. It overwrites the error return of the
function that deferred its call.
func checkId(want, got typeId)
func decAlloc(v reflect.Value) reflect.Value
decAlloc takes a value and returns a settable value that can be assigned to.
If the value is a pointer, decAlloc guarantees it points to storage.
The callers to the individual decoders are expected to have used decAlloc.
The individual decoders don't need it.
func decBool(i *decInstr, state *decoderState, value reflect.Value)
decBool decodes a uint and stores it as a boolean in value.
func decBoolArray(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decBoolSlice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decComplex128(i *decInstr, state *decoderState, value reflect.Value)
decComplex128 decodes a pair of unsigned integers, treats them as a pair of
floating point numbers, and stores them as a complex128 in value. The real
part comes first.
func decComplex128Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decComplex128Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decComplex64(i *decInstr, state *decoderState, value reflect.Value)
decComplex64 decodes a pair of unsigned integers, treats them as a pair of
floating point numbers, and stores them as a complex64 in value. The real
part comes first.
func decComplex64Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decComplex64Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decFloat32(i *decInstr, state *decoderState, value reflect.Value)
decFloat32 decodes an unsigned integer, treats it as a 32-bit floating-point
number, and stores it in value.
func decFloat32Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decFloat32Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decFloat64(i *decInstr, state *decoderState, value reflect.Value)
decFloat64 decodes an unsigned integer, treats it as a 64-bit floating-point
number, and stores it in value.
func decFloat64Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decFloat64Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decInt16(i *decInstr, state *decoderState, value reflect.Value)
decInt16 decodes an integer and stores it as an int16 in value.
func decInt16Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decInt16Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decInt32(i *decInstr, state *decoderState, value reflect.Value)
decInt32 decodes an integer and stores it as an int32 in value.
func decInt32Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decInt32Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decInt64(i *decInstr, state *decoderState, value reflect.Value)
decInt64 decodes an integer and stores it as an int64 in value.
func decInt64Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decInt64Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decInt8(i *decInstr, state *decoderState, value reflect.Value)
decInt8 decodes an integer and stores it as an int8 in value.
func decInt8Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decInt8Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decIntArray(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decIntSlice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decString(i *decInstr, state *decoderState, value reflect.Value)
decString decodes byte array and stores in value a string header describing
the data. Strings are encoded as an unsigned count followed by the raw
bytes.
func decStringArray(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decStringSlice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUint16(i *decInstr, state *decoderState, value reflect.Value)
decUint16 decodes an unsigned integer and stores it as a uint16 in value.
func decUint16Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUint16Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUint32(i *decInstr, state *decoderState, value reflect.Value)
decUint32 decodes an unsigned integer and stores it as a uint32 in value.
func decUint32Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUint32Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUint64(i *decInstr, state *decoderState, value reflect.Value)
decUint64 decodes an unsigned integer and stores it as a uint64 in value.
func decUint64Array(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUint64Slice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUint8(i *decInstr, state *decoderState, value reflect.Value)
decUint8 decodes an unsigned integer and stores it as a uint8 in value.
func decUint8Slice(i *decInstr, state *decoderState, value reflect.Value)
decUint8Slice decodes a byte slice and stores in value a slice header
describing the data. uint8 slices are encoded as an unsigned count followed
by the raw bytes.
func decUintArray(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUintSlice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUintptrArray(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decUintptrSlice(state *decoderState, v reflect.Value, length int, ovfl error) bool
func decodeIntoValue(state *decoderState, op decOp, isPtr bool, value reflect.Value, instr *decInstr) reflect.Value
decodeIntoValue is a helper for map decoding.
func decodeUintReader(r io.Reader, buf []byte) (x uint64, width int, err error)
decodeUintReader reads an encoded unsigned integer from an io.Reader.
Used only by the Decoder to read the message length.
func encBool(i *encInstr, state *encoderState, v reflect.Value)
encBool encodes the bool referenced by v as an unsigned 0 or 1.
func encBoolArray(state *encoderState, v reflect.Value) bool
func encBoolSlice(state *encoderState, v reflect.Value) bool
func encComplex(i *encInstr, state *encoderState, v reflect.Value)
encComplex encodes the complex value (complex64 complex128) referenced by v.
Complex numbers are just a pair of floating-point numbers, real part first.
func encComplex128Array(state *encoderState, v reflect.Value) bool
func encComplex128Slice(state *encoderState, v reflect.Value) bool
func encComplex64Array(state *encoderState, v reflect.Value) bool
func encComplex64Slice(state *encoderState, v reflect.Value) bool
func encFloat(i *encInstr, state *encoderState, v reflect.Value)
encFloat encodes the floating point value (float32 float64) referenced by v.
func encFloat32Array(state *encoderState, v reflect.Value) bool
func encFloat32Slice(state *encoderState, v reflect.Value) bool
func encFloat64Array(state *encoderState, v reflect.Value) bool
func encFloat64Slice(state *encoderState, v reflect.Value) bool
func encIndirect(pv reflect.Value, indir int) reflect.Value
encIndirect dereferences pv indir times and returns the result.
func encInt(i *encInstr, state *encoderState, v reflect.Value)
encInt encodes the signed integer (int int8 int16 int32 int64) referenced by
v.
func encInt16Array(state *encoderState, v reflect.Value) bool
func encInt16Slice(state *encoderState, v reflect.Value) bool
func encInt32Array(state *encoderState, v reflect.Value) bool
func encInt32Slice(state *encoderState, v reflect.Value) bool
func encInt64Array(state *encoderState, v reflect.Value) bool
func encInt64Slice(state *encoderState, v reflect.Value) bool
func encInt8Array(state *encoderState, v reflect.Value) bool
func encInt8Slice(state *encoderState, v reflect.Value) bool
func encIntArray(state *encoderState, v reflect.Value) bool
func encIntSlice(state *encoderState, v reflect.Value) bool
func encString(i *encInstr, state *encoderState, v reflect.Value)
encString encodes the string referenced by v. Strings are encoded as an
unsigned count followed by the raw bytes.
func encStringArray(state *encoderState, v reflect.Value) bool
func encStringSlice(state *encoderState, v reflect.Value) bool
func encStructTerminator(i *encInstr, state *encoderState, v reflect.Value)
encStructTerminator encodes the end of an encoded struct as delta field
number of 0.
func encUint(i *encInstr, state *encoderState, v reflect.Value)
encUint encodes the unsigned integer (uint uint8 uint16 uint32 uint64
uintptr) referenced by v.
func encUint16Array(state *encoderState, v reflect.Value) bool
func encUint16Slice(state *encoderState, v reflect.Value) bool
func encUint32Array(state *encoderState, v reflect.Value) bool
func encUint32Slice(state *encoderState, v reflect.Value) bool
func encUint64Array(state *encoderState, v reflect.Value) bool
func encUint64Slice(state *encoderState, v reflect.Value) bool
func encUint8Array(i *encInstr, state *encoderState, v reflect.Value)
encUint8Array encodes the byte array referenced by v. Byte arrays are
encoded as an unsigned count followed by the raw bytes.
func encUintArray(state *encoderState, v reflect.Value) bool
func encUintSlice(state *encoderState, v reflect.Value) bool
func encUintptrArray(state *encoderState, v reflect.Value) bool
func encUintptrSlice(state *encoderState, v reflect.Value) bool
func encodeReflectValue(state *encoderState, v reflect.Value, op encOp, indir int)
encodeReflectValue is a helper for maps. It encodes the value v.
func error_(err error)
error_ wraps the argument error and uses it as the argument to panic.
func errorf(format string, args ...any)
errorf is like error_ but takes Printf-style arguments to construct an
error. It always prefixes the message with "gob: ".
func float32FromBits(u uint64, ovfl error) float64
float32FromBits decodes an unsigned integer, treats it as a 32-bit
floating-point number, and returns it. It's a helper function for float32
and complex64. It returns a float64 because that's what reflection needs,
but its return value is known to be accurately representable in a float32.
func float64FromBits(u uint64) float64
Floating-point numbers are transmitted as uint64s holding the bits of the
underlying representation. They are sent byte-reversed, with the exponent
end coming out first, so integer floating point numbers (for example)
transmit more compactly. This routine does the unswizzling.
func floatBits(f float64) uint64
floatBits returns a uint64 holding the bits of a floating-point number.
Floating-point numbers are transmitted as uint64s holding the bits of the
underlying representation. They are sent byte-reversed, with the exponent
end coming out first, so integer floating point numbers (for example)
transmit more compactly. This routine does the swizzling.
func growSlice[E any](v reflect.Value, ps *[]E, length int)
growSlice is called for a slice that we only partially allocated, to grow it
up to length.
func ignoreTwoUints(i *decInstr, state *decoderState, v reflect.Value)
ignoreTwoUints discards a uint value with no destination. It's used to skip
complex values.
func ignoreUint(i *decInstr, state *decoderState, v reflect.Value)
ignoreUint discards a uint value with no destination.
func ignoreUint8Array(i *decInstr, state *decoderState, value reflect.Value)
ignoreUint8Array skips over the data for a byte slice value with no
destination.
func implementsInterface(typ, gobEncDecType reflect.Type) (success bool, indir int8)
implementsInterface reports whether the type implements the
gobEncoder/gobDecoder interface. It also returns the number of indirections
required to get to the implementation.
func init()
func isExported(name string) bool
isExported reports whether this is an exported - upper case - name.
func isSent(field *reflect.StructField) bool
isSent reports whether this struct field is to be transmitted. It will be
transmitted only if it is exported and not a chan or func field or pointer
to chan or func.
func overflow(name string) error
func registerBasics()
func setTypeId(typ gobType)
func toInt(x uint64) int64
toInt turns an encoded uint64 into an int, according to the marshaling
rules.
func valid(v reflect.Value) bool
valid reports whether the value is valid and a non-nil pointer. (Slices,
maps, and chans take care of themselves.)
TYPES
type CommonType struct {
Name string
Id typeId
}
CommonType holds elements of all types. It is a historical artifact, kept
for binary compatibility and exported only for the benefit of the package's
encoding of type descriptors. It is not intended for direct use by clients.
func (t *CommonType) id() typeId
func (t *CommonType) name() string
func (t *CommonType) safeString(seen map[typeId]bool) string
func (t *CommonType) setId(id typeId)
func (t *CommonType) string() string
type Decoder struct {
err error
ignoreDepth int
}
A Decoder manages the receipt of type and data information read from the
remote side of a connection. It is safe for concurrent use by multiple
goroutines.
The Decoder does only basic sanity checking on decoded input sizes,
and its limits are not configurable. Take caution when decoding gob data
from untrusted sources.
func NewDecoder(r io.Reader) *Decoder
NewDecoder returns a new decoder that reads from the io.Reader. If r does
not also implement io.ByteReader, it will be wrapped in a bufio.Reader.
func (dec *Decoder) Decode(e any) error
Decode reads the next value from the input stream and stores it in the
data represented by the empty interface value. If e is nil, the value
will be discarded. Otherwise, the value underlying e must be a pointer to
the correct type for the next data item received. If the input is at EOF,
Decode returns io.EOF and does not modify e.
func (dec *Decoder) DecodeValue(v reflect.Value) error
DecodeValue reads the next value from the input stream. If v is the zero
reflect.Value (v.Kind() == Invalid), DecodeValue discards the value.
Otherwise, it stores the value into v. In that case, v must represent a
non-nil pointer to data or be an assignable reflect.Value (v.CanSet()) If
the input is at EOF, DecodeValue returns io.EOF and does not modify v.
func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId, inProgress map[reflect.Type]typeId) bool
compatibleType asks: Are these two gob Types compatible? Answers the
question for basic types, arrays, maps and slices, plus GobEncoder/Decoder
pairs. Structs are considered ok; fields will be checked later.
func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error)
compileDec compiles the decoder engine for a value. If the value is not a
struct, it calls out to compileSingle.
func (dec *Decoder) compileIgnoreSingle(remoteId typeId) *decEngine
compileIgnoreSingle compiles the decoder engine for a non-struct top-level
value that will be discarded.
func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error)
compileSingle compiles the decoder engine for a non-struct top-level value,
including GobDecoders.
func (dec *Decoder) decIgnoreOpFor(wireId typeId, inProgress map[typeId]*decOp) *decOp
decIgnoreOpFor returns the decoding op for a field that has no destination.
func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string, inProgress map[reflect.Type]*decOp) *decOp
decOpFor returns the decoding op for the base type under rt and the
indirection count to reach it.
func (dec *Decoder) decodeArray(state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error, helper decHelper)
decodeArray decodes an array and stores it in value. The length is an
unsigned integer preceding the elements. Even though the length is redundant
(it's part of the type), it's a useful check and is included in the
encoding.
func (dec *Decoder) decodeArrayHelper(state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error, helper decHelper)
decodeArrayHelper does the work for decoding arrays and slices.
func (dec *Decoder) decodeGobDecoder(ut *userTypeInfo, state *decoderState, value reflect.Value)
decodeGobDecoder decodes something implementing the GobDecoder interface.
The data is encoded as a byte slice.
func (dec *Decoder) decodeIgnoredValue(wireId typeId)
decodeIgnoredValue decodes the data stream representing a value of the
specified type and discards it.
func (dec *Decoder) decodeInterface(ityp reflect.Type, state *decoderState, value reflect.Value)
decodeInterface decodes an interface value and stores it in value.
Interfaces are encoded as the name of a concrete type followed by a value.
If the name is empty, the value is nil and no value is sent.
func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, value reflect.Value, keyOp, elemOp decOp, ovfl error)
decodeMap decodes a map and stores it in value. Maps are encoded as a length
followed by key:value pairs. Because the internals of maps are not visible
to us, we must use reflection rather than pointer magic.
func (dec *Decoder) decodeSingle(engine *decEngine, value reflect.Value)
decodeSingle decodes a top-level value that is not a struct and stores it
in value. Such values are preceded by a zero, making them have the memory
layout of a struct field (although with an illegal field number).
func (dec *Decoder) decodeSlice(state *decoderState, value reflect.Value, elemOp decOp, ovfl error, helper decHelper)
decodeSlice decodes a slice and stores it in value. Slices are encoded as an
unsigned length followed by the elements.
func (dec *Decoder) decodeStruct(engine *decEngine, value reflect.Value)
decodeStruct decodes a top-level struct and stores it in value. Indir is
for the value, not the type. At the time of the call it may differ from
ut.indir, which was computed when the engine was built. This state cannot
arise for decodeSingle, which is called directly from the user's value,
not from the innards of an engine.
func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId
decodeTypeSequence parses: TypeSequence
(TypeDefinition DelimitedTypeDefinition*)?
and returns the type id of the next value. It returns -1 at EOF. Upon
return, the remainder of dec.buf is the value to be decoded. If this is an
interface value, it can be ignored by resetting that buffer.
func (dec *Decoder) decodeValue(wireId typeId, value reflect.Value)
decodeValue decodes the data stream representing a value and stores it in
value.
func (dec *Decoder) freeDecoderState(d *decoderState)
func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error)
getDecEnginePtr returns the engine for the specified type.
func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error)
getIgnoreEnginePtr returns the engine for the specified type when the value
is to be discarded.
func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) *decOp
gobDecodeOpFor returns the op for a type that is known to implement
GobDecoder.
func (dec *Decoder) ignoreArray(state *decoderState, elemOp decOp, length int)
ignoreArray discards the data for an array value with no destination.
func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int)
ignoreArrayHelper does the work for discarding arrays and slices.
func (dec *Decoder) ignoreGobDecoder(state *decoderState)
ignoreGobDecoder discards the data for a GobDecoder value with no
destination.
func (dec *Decoder) ignoreInterface(state *decoderState)
ignoreInterface discards the data for an interface value with no
destination.
func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp)
ignoreMap discards the data for a map value with no destination.
func (dec *Decoder) ignoreSingle(engine *decEngine)
ignoreSingle discards the data for a top-level non-struct value with no
destination. It's used when calling Decode with a nil value.
func (dec *Decoder) ignoreSlice(state *decoderState, elemOp decOp)
ignoreSlice skips over the data for a slice value with no destination.
func (dec *Decoder) ignoreStruct(engine *decEngine)
ignoreStruct discards the data for a struct with no destination.
func (dec *Decoder) newDecoderState(buf *decBuffer) *decoderState
We pass the bytes.Buffer separately for easier testing of the infrastructure
without requiring a full Decoder.
func (dec *Decoder) nextInt() int64
func (dec *Decoder) nextUint() uint64
func (dec *Decoder) readMessage(nbytes int)
readMessage reads the next nbytes bytes from the input.
func (dec *Decoder) recvMessage() bool
recvMessage reads the next count-delimited item from the input. It is the
converse of Encoder.writeMessage. It returns false on EOF or other error
reading the message.
func (dec *Decoder) recvType(id typeId)
recvType loads the definition of a type.
func (dec *Decoder) typeString(remoteId typeId) string
typeString returns a human-readable description of the type identified by
remoteId.
type Encoder struct {
err error
}
An Encoder manages the transmission of type and data information to the
other side of a connection. It is safe for concurrent use by multiple
goroutines.
func NewEncoder(w io.Writer) *Encoder
NewEncoder returns a new encoder that will transmit on the io.Writer.
func (enc *Encoder) Encode(e any) error
Encode transmits the data item represented by the empty interface value,
guaranteeing that all necessary type information has been transmitted first.
Passing a nil pointer to Encoder will panic, as they cannot be transmitted
by gob.
func (enc *Encoder) EncodeValue(value reflect.Value) error
EncodeValue transmits the data item represented by the reflection value,
guaranteeing that all necessary type information has been transmitted first.
Passing a nil pointer to EncodeValue will panic, as they cannot be
transmitted by gob.
func (enc *Encoder) encode(b *encBuffer, value reflect.Value, ut *userTypeInfo)
func (enc *Encoder) encodeArray(b *encBuffer, value reflect.Value, op encOp, elemIndir int, length int, helper encHelper)
encodeArray encodes an array.
func (enc *Encoder) encodeGobEncoder(b *encBuffer, ut *userTypeInfo, v reflect.Value)
encodeGobEncoder encodes a value that implements the GobEncoder interface.
The data is sent as a byte array.
func (enc *Encoder) encodeInterface(b *encBuffer, iv reflect.Value)
encodeInterface encodes the interface value iv. To send an interface,
we send a string identifying the concrete type, followed by the type
identifier (which might require defining that type right now), followed by
the concrete value. A nil value gets sent as the empty string for the name,
followed by no value.
func (enc *Encoder) encodeMap(b *encBuffer, mv reflect.Value, keyOp, elemOp encOp, keyIndir, elemIndir int)
encodeMap encodes a map as unsigned count followed by key:value pairs.
func (enc *Encoder) encodeSingle(b *encBuffer, engine *encEngine, value reflect.Value)
encodeSingle encodes a single top-level non-struct value.
func (enc *Encoder) encodeStruct(b *encBuffer, engine *encEngine, value reflect.Value)
encodeStruct encodes a single struct value.
func (enc *Encoder) freeEncoderState(e *encoderState)
func (enc *Encoder) newEncoderState(b *encBuffer) *encoderState
func (enc *Encoder) popWriter()
popWriter pops the innermost writer.
func (enc *Encoder) pushWriter(w io.Writer)
pushWriter adds a writer to the encoder.
func (enc *Encoder) sendActualType(w io.Writer, state *encoderState, ut *userTypeInfo, actual reflect.Type) (sent bool)
sendActualType sends the requested type, without further investigation,
unless it's been sent before.
func (enc *Encoder) sendType(w io.Writer, state *encoderState, origt reflect.Type) (sent bool)
sendType sends the type info to the other side, if necessary.
func (enc *Encoder) sendTypeDescriptor(w io.Writer, state *encoderState, ut *userTypeInfo)
sendTypeDescriptor makes sure the remote side knows about this type.
It will send a descriptor if this is the first time the type has been sent.
func (enc *Encoder) sendTypeId(state *encoderState, ut *userTypeInfo)
sendTypeId sends the id, which must have already been defined.
func (enc *Encoder) setError(err error)
func (enc *Encoder) writeMessage(w io.Writer, b *encBuffer)
writeMessage sends the data item preceded by an unsigned count of its
length.
func (enc *Encoder) writer() io.Writer
writer returns the innermost writer the encoder is using.
type GobDecoder interface {
GobDecode([]byte) error
}
GobDecoder is the interface describing data that provides its own routine
for decoding transmitted values sent by a GobEncoder.
type GobEncoder interface {
GobEncode() ([]byte, error)
}
GobEncoder is the interface describing data that provides its own
representation for encoding values for transmission to a GobDecoder. A type
that implements GobEncoder and GobDecoder has complete control over the
representation of its data and may therefore contain things such as private
fields, channels, and functions, which are not usually transmissible in gob
streams.
Note: Since gobs can be stored permanently, it is good design to guarantee
the encoding used by a GobEncoder is stable as the software evolves.
For instance, it might make sense for GobEncode to include a version number
in the encoding.
type arrayType struct {
CommonType
Elem typeId
Len int
}
Array type
func newArrayType(name string) *arrayType
func (a *arrayType) init(elem gobType, len int)
func (a *arrayType) safeString(seen map[typeId]bool) string
func (a *arrayType) string() string
type decBuffer struct {
data []byte
}
decBuffer is an extremely simple, fast implementation of a read-only byte
buffer. It is initialized by calling Size and then copying the data into the
slice returned by Bytes().
func (d *decBuffer) Bytes() []byte
func (d *decBuffer) Drop(n int)
func (d *decBuffer) Len() int
func (d *decBuffer) Read(p []byte) (int, error)
func (d *decBuffer) ReadByte() (byte, error)
func (d *decBuffer) Reset()
func (d *decBuffer) SetBytes(data []byte)
SetBytes sets the buffer to the bytes, discarding any existing data.
type decEngine struct {
instr []decInstr
}
The encoder engine is an array of instructions indexed by field number of
the incoming decoder. It is executed with random access according to field
number.
type decHelper func(state *decoderState, v reflect.Value, length int, ovfl error) bool
type decInstr struct {
op decOp
}
The 'instructions' of the decoding machine
type decOp func(i *decInstr, state *decoderState, v reflect.Value)
decOp is the signature of a decoding operator for a given type.
type decoderState struct {
dec *Decoder
b *decBuffer
}
decoderState is the execution state of an instance of the decoder. A new
state is created for nested objects.
func (state *decoderState) decodeInt() int64
decodeInt reads an encoded signed integer from state.r. Does not check for
overflow.
func (state *decoderState) decodeUint() (x uint64)
decodeUint reads an encoded unsigned integer from state.r. Does not check
for overflow.
func (state *decoderState) getLength() (int, bool)
getLength decodes the next uint and makes sure it is a possible size for a
data item that follows, which means it must fit in a non-negative int and
fit in the buffer.
type emptyStruct struct{}
emptyStruct is the type we compile into when ignoring a struct value.
type encBuffer struct {
data []byte
scratch [64]byte
}
encBuffer is an extremely simple, fast implementation of a write-only byte
buffer. It never returns a non-nil error, but Write returns an error value
so it matches io.Writer.
func (e *encBuffer) Bytes() []byte
func (e *encBuffer) Len() int
func (e *encBuffer) Reset()
func (e *encBuffer) Write(p []byte) (int, error)
func (e *encBuffer) WriteString(s string)
func (e *encBuffer) writeByte(c byte)
type encEngine struct {
instr []encInstr
}
encEngine an array of instructions indexed by field number of the encoding
data, typically a struct. It is executed top to bottom, walking the struct.
func buildEncEngine(info *typeInfo, ut *userTypeInfo, building map[*typeInfo]bool) *encEngine
func compileEnc(ut *userTypeInfo, building map[*typeInfo]bool) *encEngine
compileEnc returns the engine to compile the type.
func getEncEngine(ut *userTypeInfo, building map[*typeInfo]bool) *encEngine
getEncEngine returns the engine to compile the type.
type encHelper func(state *encoderState, v reflect.Value) bool
type encInstr struct {
op encOp
}
The 'instructions' of the encoding machine
type encOp func(i *encInstr, state *encoderState, v reflect.Value)
encOp is the signature of an encoding operator for a given type.
func encOpFor(rt reflect.Type, inProgress map[reflect.Type]*encOp, building map[*typeInfo]bool) (*encOp, int)
encOpFor returns (a pointer to) the encoding op for the base type under rt
and the indirection count to reach it.
func gobEncodeOpFor(ut *userTypeInfo) (*encOp, int)
gobEncodeOpFor returns the op for a type that is known to implement
GobEncoder.
type encoderState struct {
enc *Encoder
b *encBuffer
}
encoderState is the global execution state of an instance of the encoder.
Field numbers are delta encoded and always increase. The field number is
initialized to -1 so 0 comes out as delta(1). A delta of 0 terminates the
structure.
func (state *encoderState) encodeInt(i int64)
encodeInt writes an encoded signed integer to state.w. The low bit of the
encoding says whether to bit complement the (other bits of the) uint to
recover the int.
func (state *encoderState) encodeUint(x uint64)
encodeUint writes an encoded unsigned integer to state.b.
func (state *encoderState) update(instr *encInstr)
update emits a field number and updates the state to record its value for
delta encoding. If the instruction pointer is nil, it does nothing
type fieldType struct {
Name string
Id typeId
}
Struct type
type gobEncoderType struct {
CommonType
}
GobEncoder type (something that implements the GobEncoder interface)
func newGobEncoderType(name string) *gobEncoderType
func (g *gobEncoderType) safeString(seen map[typeId]bool) string
func (g *gobEncoderType) string() string
type gobError struct {
err error
}
A gobError is used to distinguish errors (panics) generated in this package.
type gobType interface {
id() typeId
setId(id typeId)
name() string
safeString(seen map[typeId]bool) string
}
func builtinIdToType(id typeId) gobType
func getBaseType(name string, rt reflect.Type) (gobType, error)
getBaseType returns the Gob type describing the given reflect.Type's base
type. typeLock must be held.
func getType(name string, ut *userTypeInfo, rt reflect.Type) (gobType, error)
getType returns the Gob type describing the given reflect.Type. Should be
called only when handling GobEncoders/Decoders, which may be pointers.
All other types are handled through the base type, never a pointer. typeLock
must be held.
func idToType(id typeId) gobType
func newTypeObject(name string, ut *userTypeInfo, rt reflect.Type) (gobType, error)
newTypeObject allocates a gobType for the reflection type rt. Unless ut
represents a GobEncoder, rt should be the base type of ut. This is only
called from the encoding side. The decoding side works through typeIds and
userTypeInfos alone.
type mapType struct {
CommonType
Key typeId
Elem typeId
}
Map type
func newMapType(name string) *mapType
func (m *mapType) init(key, elem gobType)
func (m *mapType) safeString(seen map[typeId]bool) string
func (m *mapType) string() string
type sliceType struct {
CommonType
Elem typeId
}
Slice type
func newSliceType(name string) *sliceType
func (s *sliceType) init(elem gobType)
func (s *sliceType) safeString(seen map[typeId]bool) string
func (s *sliceType) string() string
type structType struct {
CommonType
Field []fieldType
}
func newStructType(name string) *structType
func (s *structType) safeString(seen map[typeId]bool) string
func (s *structType) string() string
type typeId int32
A typeId represents a gob Type as an integer that can be passed on the wire.
Internally, typeIds are used as keys to a map to recover the underlying type
info.
func bootstrapType(name string, e any) typeId
used for building the basic types; called only from init(). the incoming
interface always refers to a pointer.
func (t typeId) gobType() gobType
func (t typeId) name() string
Name returns the name of the type associated with the typeId.
func (t typeId) string() string
string returns the string representation of the type associated with the
typeId.
type typeInfo struct {
id typeId
encoder atomic.Pointer[encEngine]
wire wireType
}
func buildTypeInfo(ut *userTypeInfo, rt reflect.Type) (*typeInfo, error)
buildTypeInfo constructs the type information for the type and stores it in
the type info map.
func getTypeInfo(ut *userTypeInfo) (*typeInfo, error)
func lookupTypeInfo(rt reflect.Type) *typeInfo
func mustGetTypeInfo(rt reflect.Type) *typeInfo
Called only when a panic is acceptable and unexpected.
type userTypeInfo struct {
}
userTypeInfo stores the information associated with a type the user has
handed to the package. It's computed once and stored in a map keyed by
reflection type.
func userType(rt reflect.Type) *userTypeInfo
userType returns, and saves, the information associated with user-provided
type rt. If the user type is not valid, it calls error.
func validUserType(rt reflect.Type) (*userTypeInfo, error)
validUserType returns, and saves, the information associated with
user-provided type rt. If the user type is not valid, err will be non-nil.
To be used when the error handler is not set up.
type wireType struct {
ArrayT *arrayType
SliceT *sliceType
StructT *structType
MapT *mapType
GobEncoderT *gobEncoderType
BinaryMarshalerT *gobEncoderType
TextMarshalerT *gobEncoderType
}
Representation of the information we send and receive about this type.
Each value we send is preceded by its type definition: an encoded int.
However, the very first time we send the value, we first send the pair (-id,
wireType). For bootstrapping purposes, we assume that the recipient
knows how to decode a wireType; it is exactly the wireType struct here,
interpreted using the gob rules for sending a structure, except that we
assume the ids for wireType and structType etc. are known. The relevant
pieces are built in encode.go's init() function. To maintain binary
compatibility, if you extend this type, always put the new fields last.
func (w *wireType) string() string
encoding/hex
func AppendDecode(dst, src []byte) ([]byte, error)
AppendDecode appends the hexadecimally decoded src to dst and returns the
extended buffer. If the input is malformed, it returns the partially decoded
src and an error.
func AppendEncode(dst, src []byte) []byte
AppendEncode appends the hexadecimally encoded src to dst and returns the
extended buffer.
func Decode(dst, src []byte) (int, error)
Decode decodes src into DecodedLen(len(src)) bytes, returning the actual
number of bytes written to dst.
Decode expects that src contains only hexadecimal characters and that src
has even length. If the input is malformed, Decode returns the number of
bytes decoded before the error.
func DecodeString(s string) ([]byte, error)
DecodeString returns the bytes represented by the hexadecimal string s.
DecodeString expects that src contains only hexadecimal characters and that
src has even length. If the input is malformed, DecodeString returns the
bytes decoded before the error.
func DecodedLen(x int) int
DecodedLen returns the length of a decoding of x source bytes. Specifically,
it returns x / 2.
func Dump(data []byte) string
Dump returns a string that contains a hex dump of the given data. The format
of the hex dump matches the output of `hexdump -C` on the command line.
func Dumper(w io.Writer) io.WriteCloser
Dumper returns a io.WriteCloser that writes a hex dump of all written data
to w. The format of the dump matches the output of `hexdump -C` on the
command line.
func Encode(dst, src []byte) int
Encode encodes src into EncodedLen(len(src)) bytes of dst. As a convenience,
it returns the number of bytes written to dst, but this value is always
EncodedLen(len(src)). Encode implements hexadecimal encoding.
func EncodeToString(src []byte) string
EncodeToString returns the hexadecimal encoding of src.
func EncodedLen(n int) int
EncodedLen returns the length of an encoding of n source bytes.
Specifically, it returns n * 2.
func NewDecoder(r io.Reader) io.Reader
NewDecoder returns an io.Reader that decodes hexadecimal characters from r.
NewDecoder expects that r contain only an even number of hexadecimal
characters.
func NewEncoder(w io.Writer) io.Writer
NewEncoder returns an io.Writer that writes lowercase hexadecimal characters
to w.
func toChar(b byte) byte
TYPES
type InvalidByteError byte
InvalidByteError values describe errors resulting from an invalid byte in a
hex string.
func (e InvalidByteError) Error() string
type decoder struct {
r io.Reader
err error
}
func (d *decoder) Read(p []byte) (n int, err error)
type dumper struct {
w io.Writer
rightChars [18]byte
buf [14]byte
closed bool
}
func (h *dumper) Close() (err error)
func (h *dumper) Write(data []byte) (n int, err error)
type encoder struct {
w io.Writer
err error
}
func (e *encoder) Write(p []byte) (n int, err error)
encoding/json
func Compact(dst *bytes.Buffer, src []byte) error
Compact appends to dst the JSON-encoded src with insignificant space
characters elided.
func HTMLEscape(dst *bytes.Buffer, src []byte)
HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and
U+2029 characters inside string literals changed to \u003c, \u003e, \u0026,
\u2028, \u2029 so that the JSON will be safe to embed inside HTML <script>
tags. For historical reasons, web browsers don't honor standard HTML
escaping within <script> tags, so an alternative JSON encoding must be used.
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
Indent appends to dst an indented form of the JSON-encoded src. Each element
in a JSON object or array begins on a new, indented line beginning with
prefix followed by one or more copies of indent according to the indentation
nesting. The data appended to dst does not begin with the prefix nor any
indentation, to make it easier to embed inside other formatted JSON data.
Although leading space characters (space, tab, carriage return, newline) at
the beginning of src are dropped, trailing space characters at the end of
src are preserved and copied to dst. For example, if src has no trailing
spaces, neither will dst; if src ends in a trailing newline, so will dst.
func Marshal(v any) ([]byte, error)
Marshal returns the JSON encoding of v.
Marshal traverses the value v recursively. If an encountered
value implements Marshaler and is not a nil pointer, Marshal calls
[Marshaler.MarshalJSON] to produce JSON. If no [Marshaler.MarshalJSON]
method is present but the value implements encoding.TextMarshaler instead,
Marshal calls encoding.TextMarshaler.MarshalText and encodes the
result as a JSON string. The nil pointer exception is not strictly
necessary but mimics a similar, necessary exception in the behavior of
[Unmarshaler.UnmarshalJSON].
Otherwise, Marshal uses the following type-dependent default encodings:
Boolean values encode as JSON booleans.
Floating point, integer, and Number values encode as JSON numbers. NaN and
+/-Inf values will return an UnsupportedValueError.
String values encode as JSON strings coerced to valid UTF-8, replacing
invalid bytes with the Unicode replacement rune. So that the JSON will
be safe to embed inside HTML <script> tags, the string is encoded using
HTMLEscape, which replaces "<", ">", "&", U+2028, and U+2029 are escaped to
"\u003c","\u003e", "\u0026", "\u2028", and "\u2029". This replacement can be
disabled when using an Encoder, by calling Encoder.SetEscapeHTML(false).
Array and slice values encode as JSON arrays, except that []byte encodes as
a base64-encoded string, and a nil slice encodes as the null JSON value.
Struct values encode as JSON objects. Each exported struct field becomes
a member of the object, using the field name as the object key, unless the
field is omitted for one of the reasons given below.
The encoding of each struct field can be customized by the format string
stored under the "json" key in the struct field's tag. The format string
gives the name of the field, possibly followed by a comma-separated list
of options. The name may be empty in order to specify options without
overriding the default field name.
The "omitempty" option specifies that the field should be omitted from
the encoding if the field has an empty value, defined as false, 0,
a nil pointer, a nil interface value, and any array, slice, map, or string
of length zero.
As a special case, if the field tag is "-", the field is always omitted.
Note that a field with name "-" can still be generated using the tag "-,".
Examples of struct field tags and their meanings:
Field int `json:"myName"`
Field int `json:"myName,omitempty"`
Field int `json:",omitempty"`
Field int `json:"-"`
Field int `json:"-,"`
The "omitzero" option specifies that the field should be omitted from the
encoding if the field has a zero value, according to rules:
1) If the field type has an "IsZero() bool" method, that will be used to
determine whether the value is zero.
2) Otherwise, the value is zero if it is the zero value for its type.
If both "omitempty" and "omitzero" are specified, the field will be omitted
if the value is either empty or zero (or both).
The "string" option signals that a field is stored as JSON inside a
JSON-encoded string. It applies only to fields of string, floating point,
integer, or boolean types. This extra level of encoding is sometimes used
when communicating with JavaScript programs:
Int64String int64 `json:",string"`
The key name will be used if it's a non-empty string consisting of only
Unicode letters, digits, and ASCII punctuation except quotation marks,
backslash, and comma.
Embedded struct fields are usually marshaled as if their inner exported
fields were fields in the outer struct, subject to the usual Go visibility
rules amended as described in the next paragraph. An anonymous struct field
with a name given in its JSON tag is treated as having that name, rather
than being anonymous. An anonymous struct field of interface type is treated
the same as having that type as its name, rather than being anonymous.
The Go visibility rules for struct fields are amended for JSON when deciding
which field to marshal or unmarshal. If there are multiple fields at the
same level, and that level is the least nested (and would therefore be the
nesting level selected by the usual Go rules), the following extra rules
apply:
1) Of those fields, if any are JSON-tagged, only tagged fields are
considered, even if there are multiple untagged fields that would otherwise
conflict.
2) If there is exactly one field (tagged or not according to the first
rule), that is selected.
3) Otherwise there are multiple fields, and all are ignored; no error
occurs.
Handling of anonymous struct fields is new in Go 1.1. Prior to Go 1.1,
anonymous struct fields were ignored. To force ignoring of an anonymous
struct field in both current and earlier versions, give the field a JSON tag
of "-".
Map values encode as JSON objects. The map's key type must either be a
string, an integer type, or implement encoding.TextMarshaler. The map keys
are sorted and used as JSON object keys by applying the following rules,
subject to the UTF-8 coercion described for string values above:
- keys of any string type are used directly
- keys that implement encoding.TextMarshaler are marshaled
- integer keys are converted to strings
Pointer values encode as the value pointed to. A nil pointer encodes as the
null JSON value.
Interface values encode as the value contained in the interface. A nil
interface value encodes as the null JSON value.
Channel, complex, and function values cannot be encoded in JSON. Attempting
to encode such a value causes Marshal to return an UnsupportedTypeError.
JSON cannot represent cyclic data structures and Marshal does not handle
them. Passing cyclic structures to Marshal will result in an error.
func MarshalIndent(v any, prefix, indent string) ([]byte, error)
MarshalIndent is like Marshal but applies Indent to format the output.
Each JSON element in the output will begin on a new line beginning with
prefix followed by one or more copies of indent according to the indentation
nesting.
func Unmarshal(data []byte, v any) error
Unmarshal parses the JSON-encoded data and stores the result in the
value pointed to by v. If v is nil or not a pointer, Unmarshal returns an
InvalidUnmarshalError.
Unmarshal uses the inverse of the encodings that Marshal uses, allocating
maps, slices, and pointers as necessary, with the following additional
rules:
To unmarshal JSON into a pointer, Unmarshal first handles the case of the
JSON being the JSON literal null. In that case, Unmarshal sets the pointer
to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at
by the pointer. If the pointer is nil, Unmarshal allocates a new value for
it to point to.
To unmarshal JSON into a value implementing Unmarshaler, Unmarshal
calls that value's [Unmarshaler.UnmarshalJSON] method, including
when the input is a JSON null. Otherwise, if the value implements
encoding.TextUnmarshaler and the input is a JSON quoted string, Unmarshal
calls encoding.TextUnmarshaler.UnmarshalText with the unquoted form of the
string.
To unmarshal JSON into a struct, Unmarshal matches incoming object keys
to the keys used by Marshal (either the struct field name or its tag),
preferring an exact match but also accepting a case-insensitive match.
By default, object keys which don't have a corresponding struct field are
ignored (see Decoder.DisallowUnknownFields for an alternative).
To unmarshal JSON into an interface value, Unmarshal stores one of these in
the interface value:
- bool, for JSON booleans
- float64, for JSON numbers
- string, for JSON strings
- []any, for JSON arrays
- map[string]any, for JSON objects
- nil for JSON null
To unmarshal a JSON array into a slice, Unmarshal resets the slice length
to zero and then appends each element to the slice. As a special case,
to unmarshal an empty JSON array into a slice, Unmarshal replaces the slice
with a new empty slice.
To unmarshal a JSON array into a Go array, Unmarshal decodes JSON array
elements into corresponding Go array elements. If the Go array is smaller
than the JSON array, the additional JSON array elements are discarded.
If the JSON array is smaller than the Go array, the additional Go array
elements are set to zero values.
To unmarshal a JSON object into a map, Unmarshal first establishes
a map to use. If the map is nil, Unmarshal allocates a new map.
Otherwise Unmarshal reuses the existing map, keeping existing entries.
Unmarshal then stores key-value pairs from the JSON object into the map.
The map's key type must either be any string type, an integer, or implement
encoding.TextUnmarshaler.
If the JSON-encoded data contain a syntax error, Unmarshal returns a
SyntaxError.
If a JSON value is not appropriate for a given target type, or if a JSON
number overflows the target type, Unmarshal skips that field and completes
the unmarshaling as best it can. If no more serious errors are encountered,
Unmarshal returns an UnmarshalTypeError describing the earliest such error.
In any case, it's not guaranteed that all the remaining fields following the
problematic one will be unmarshaled into the target object.
The JSON null value unmarshals into an interface, map, pointer, or slice
by setting that Go value to nil. Because null is often used in JSON to mean
“not present,” unmarshaling a JSON null into any other Go type has no effect
on the value and produces no error.
When unmarshaling quoted strings, invalid UTF-8 or invalid UTF-16 surrogate
pairs are not treated as an error. Instead, they are replaced by the Unicode
replacement character U+FFFD.
func Valid(data []byte) bool
Valid reports whether data is a valid JSON encoding.
func addrMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts)
func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts)
func appendCompact(dst, src []byte, escape bool) ([]byte, error)
func appendFoldedName(out, in []byte) []byte
func appendHTMLEscape(dst, src []byte) []byte
func appendIndent(dst, src []byte, prefix, indent string) ([]byte, error)
func appendNewline(dst []byte, prefix, indent string, depth int) []byte
func appendString[Bytes []byte | string](dst []byte, src Bytes, escapeHTML bool) []byte
func boolEncoder(e *encodeState, v reflect.Value, opts encOpts)
func checkValid(data []byte, scan *scanner) error
checkValid verifies that data is valid JSON-encoded data. scan is passed in
for use by checkValid to avoid an allocation. checkValid returns nil or a
SyntaxError.
func encodeByteSlice(e *encodeState, v reflect.Value, _ encOpts)
func foldName(in []byte) []byte
foldName returns a folded string such that foldName(x) == foldName(y) is
identical to bytes.EqualFold(x, y).
func foldRune(r rune) rune
foldRune is returns the smallest rune for all runes in the same fold set.
func freeScanner(scan *scanner)
func getu4(s []byte) rune
getu4 decodes \uXXXX from the beginning of s, returning the hex value,
or it returns -1.
func intEncoder(e *encodeState, v reflect.Value, opts encOpts)
func interfaceEncoder(e *encodeState, v reflect.Value, opts encOpts)
func invalidValueEncoder(e *encodeState, v reflect.Value, _ encOpts)
func isEmptyValue(v reflect.Value) bool
func isSpace(c byte) bool
func isValidNumber(s string) bool
isValidNumber reports whether s is a valid JSON number literal.
isValidNumber should be an internal detail, but widely used packages access
it using linkname. Notable members of the hall of shame include:
- github.com/bytedance/sonic
Do not remove or change the type signature. See go.dev/issue/67401.
func isValidTag(s string) bool
func marshalerEncoder(e *encodeState, v reflect.Value, opts encOpts)
func mayAppendQuote(b []byte, quoted bool) []byte
func nonSpace(b []byte) bool
func quoteChar(c byte) string
quoteChar formats c as a quoted character literal.
func resolveKeyName(k reflect.Value) (string, error)
func state0(s *scanner, c byte) int
state0 is the state after reading `0` during a number.
func state1(s *scanner, c byte) int
state1 is the state after reading a non-zero integer during a number,
such as after reading `1` or `100` but not `0`.
func stateBeginString(s *scanner, c byte) int
stateBeginString is the state after reading `{"key": value,`.
func stateBeginStringOrEmpty(s *scanner, c byte) int
stateBeginStringOrEmpty is the state after reading `{`.
func stateBeginValue(s *scanner, c byte) int
stateBeginValue is the state at the beginning of the input.
func stateBeginValueOrEmpty(s *scanner, c byte) int
stateBeginValueOrEmpty is the state after reading `[`.
func stateDot(s *scanner, c byte) int
stateDot is the state after reading the integer and decimal point in a
number, such as after reading `1.`.
func stateDot0(s *scanner, c byte) int
stateDot0 is the state after reading the integer, decimal point, and
subsequent digits of a number, such as after reading `3.14`.
func stateE(s *scanner, c byte) int
stateE is the state after reading the mantissa and e in a number, such as
after reading `314e` or `0.314e`.
func stateE0(s *scanner, c byte) int
stateE0 is the state after reading the mantissa, e, optional sign, and at
least one digit of the exponent in a number, such as after reading `314e-2`
or `0.314e+1` or `3.14e0`.
func stateESign(s *scanner, c byte) int
stateESign is the state after reading the mantissa, e, and sign in a number,
such as after reading `314e-` or `0.314e+`.
func stateEndTop(s *scanner, c byte) int
stateEndTop is the state after finishing the top-level value, such as after
reading `{}` or `[1,2,3]`. Only space characters should be seen now.
func stateEndValue(s *scanner, c byte) int
stateEndValue is the state after completing a value, such as after reading
`{}` or `true` or `["x"`.
func stateError(s *scanner, c byte) int
stateError is the state after reaching a syntax error, such as after reading
`[1}` or `5.1.2`.
func stateF(s *scanner, c byte) int
stateF is the state after reading `f`.
func stateFa(s *scanner, c byte) int
stateFa is the state after reading `fa`.
func stateFal(s *scanner, c byte) int
stateFal is the state after reading `fal`.
func stateFals(s *scanner, c byte) int
stateFals is the state after reading `fals`.
func stateInString(s *scanner, c byte) int
stateInString is the state after reading `"`.
func stateInStringEsc(s *scanner, c byte) int
stateInStringEsc is the state after reading `"\` during a quoted string.
func stateInStringEscU(s *scanner, c byte) int
stateInStringEscU is the state after reading `"\u` during a quoted string.
func stateInStringEscU1(s *scanner, c byte) int
stateInStringEscU1 is the state after reading `"\u1` during a quoted string.
func stateInStringEscU12(s *scanner, c byte) int
stateInStringEscU12 is the state after reading `"\u12` during a quoted
string.
func stateInStringEscU123(s *scanner, c byte) int
stateInStringEscU123 is the state after reading `"\u123` during a quoted
string.
func stateN(s *scanner, c byte) int
stateN is the state after reading `n`.
func stateNeg(s *scanner, c byte) int
stateNeg is the state after reading `-` during a number.
func stateNu(s *scanner, c byte) int
stateNu is the state after reading `nu`.
func stateNul(s *scanner, c byte) int
stateNul is the state after reading `nul`.
func stateT(s *scanner, c byte) int
stateT is the state after reading `t`.
func stateTr(s *scanner, c byte) int
stateTr is the state after reading `tr`.
func stateTru(s *scanner, c byte) int
stateTru is the state after reading `tru`.
func stringEncoder(e *encodeState, v reflect.Value, opts encOpts)
func textMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts)
func typeByIndex(t reflect.Type, index []int) reflect.Type
func uintEncoder(e *encodeState, v reflect.Value, opts encOpts)
func unquote(s []byte) (t string, ok bool)
unquote converts a quoted JSON string literal s into an actual string t.
The rules are different than for Go, so cannot use strconv.Unquote.
func unquoteBytes(s []byte) (t []byte, ok bool)
unquoteBytes should be an internal detail, but widely used packages access
it using linkname. Notable members of the hall of shame include:
- github.com/bytedance/sonic
Do not remove or change the type signature. See go.dev/issue/67401.
func unsupportedTypeEncoder(e *encodeState, v reflect.Value, _ encOpts)
TYPES
type Decoder struct {
r io.Reader
buf []byte
d decodeState
scan scanner
err error
tokenState int
tokenStack []int
}
A Decoder reads and decodes JSON values from an input stream.
func NewDecoder(r io.Reader) *Decoder
NewDecoder returns a new decoder that reads from r.
The decoder introduces its own buffering and may read data from r beyond the
JSON values requested.
func (dec *Decoder) Buffered() io.Reader
Buffered returns a reader of the data remaining in the Decoder's buffer.
The reader is valid until the next call to Decoder.Decode.
func (dec *Decoder) Decode(v any) error
Decode reads the next JSON-encoded value from its input and stores it in the
value pointed to by v.
See the documentation for Unmarshal for details about the conversion of JSON
into a Go value.
func (dec *Decoder) DisallowUnknownFields()
DisallowUnknownFields causes the Decoder to return an error when the
destination is a struct and the input contains object keys which do not
match any non-ignored, exported fields in the destination.
func (dec *Decoder) InputOffset() int64
InputOffset returns the input stream byte offset of the current decoder
position. The offset gives the location of the end of the most recently
returned token and the beginning of the next token.
func (dec *Decoder) More() bool
More reports whether there is another element in the current array or object
being parsed.
func (dec *Decoder) Token() (Token, error)
Token returns the next JSON token in the input stream. At the end of the
input stream, Token returns nil, io.EOF.
Token guarantees that the delimiters [ ] { } it returns are properly nested
and matched: if Token encounters an unexpected delimiter in the input,
it will return an error.
The input stream consists of basic JSON values—bool, string, number,
and null—along with delimiters [ ] { } of type Delim to mark the start and
end of arrays and objects. Commas and colons are elided.
func (dec *Decoder) UseNumber()
UseNumber causes the Decoder to unmarshal a number into an interface value
as a Number instead of as a float64.
func (dec *Decoder) peek() (byte, error)
func (dec *Decoder) readValue() (int, error)
readValue reads a JSON value into dec.buf. It returns the length of the
encoding.
func (dec *Decoder) refill() error
func (dec *Decoder) tokenError(c byte) (Token, error)
func (dec *Decoder) tokenPrepareForDecode() error
advance tokenstate from a separator state to a value state
func (dec *Decoder) tokenValueAllowed() bool
func (dec *Decoder) tokenValueEnd()
type Delim rune
A Delim is a JSON array or object delimiter, one of [ ] { or }.
func (d Delim) String() string
type Encoder struct {
w io.Writer
err error
escapeHTML bool
indentBuf []byte
indentPrefix string
indentValue string
}
An Encoder writes JSON values to an output stream.
func NewEncoder(w io.Writer) *Encoder
NewEncoder returns a new encoder that writes to w.
func (enc *Encoder) Encode(v any) error
Encode writes the JSON encoding of v to the stream, with insignificant space
characters elided, followed by a newline character.
See the documentation for Marshal for details about the conversion of Go
values to JSON.
func (enc *Encoder) SetEscapeHTML(on bool)
SetEscapeHTML specifies whether problematic HTML characters should be
escaped inside JSON quoted strings. The default behavior is to escape &, <,
and > to \u0026, \u003c, and \u003e to avoid certain safety problems that
can arise when embedding JSON in HTML.
In non-HTML settings where the escaping interferes with the readability of
the output, SetEscapeHTML(false) disables this behavior.
func (enc *Encoder) SetIndent(prefix, indent string)
SetIndent instructs the encoder to format each subsequent encoded value as
if indented by the package-level function Indent(dst, src, prefix, indent).
Calling SetIndent("", "") disables indentation.
type InvalidUTF8Error struct {
}
Before Go 1.2, an InvalidUTF8Error was returned by Marshal when attempting
to encode a string value with invalid UTF-8 sequences. As of Go 1.2,
Marshal instead coerces the string to valid UTF-8 by replacing invalid bytes
with the Unicode replacement rune U+FFFD.
Deprecated: No longer used; kept for compatibility.
func (e *InvalidUTF8Error) Error() string
type InvalidUnmarshalError struct {
Type reflect.Type
}
An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
(The argument to Unmarshal must be a non-nil pointer.)
func (e *InvalidUnmarshalError) Error() string
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
Marshaler is the interface implemented by types that can marshal themselves
into valid JSON.
var _ Marshaler = (*RawMessage)(nil)
type MarshalerError struct {
Type reflect.Type
Err error
sourceFunc string
}
A MarshalerError represents an error from calling a [Marshaler.MarshalJSON]
or encoding.TextMarshaler.MarshalText method.
func (e *MarshalerError) Error() string
func (e *MarshalerError) Unwrap() error
Unwrap returns the underlying error.
type Number string
A Number represents a JSON number literal.
func (n Number) Float64() (float64, error)
Float64 returns the number as a float64.
func (n Number) Int64() (int64, error)
Int64 returns the number as an int64.
func (n Number) String() string
String returns the literal text of the number.
type RawMessage []byte
RawMessage is a raw encoded JSON value. It implements Marshaler and
Unmarshaler and can be used to delay JSON decoding or precompute a JSON
encoding.
func (m RawMessage) MarshalJSON() ([]byte, error)
MarshalJSON returns m as the JSON encoding of m.
func (m *RawMessage) UnmarshalJSON(data []byte) error
UnmarshalJSON sets *m to a copy of data.
type SyntaxError struct {
}
A SyntaxError is a description of a JSON syntax error. Unmarshal will return
a SyntaxError if the JSON can't be parsed.
func (e *SyntaxError) Error() string
type Token any
A Token holds a value of one of these types:
- Delim, for the four JSON delimiters [ ] { }
- bool, for JSON booleans
- float64, for JSON numbers
- Number, for JSON numbers
- string, for JSON string literals
- nil, for JSON null
type UnmarshalFieldError struct {
Key string
Type reflect.Type
Field reflect.StructField
}
An UnmarshalFieldError describes a JSON object key that led to an unexported
(and therefore unwritable) struct field.
Deprecated: No longer used; kept for compatibility.
func (e *UnmarshalFieldError) Error() string
type UnmarshalTypeError struct {
}
An UnmarshalTypeError describes a JSON value that was not appropriate for a
value of a specific Go type.
func (e *UnmarshalTypeError) Error() string
type Unmarshaler interface {
UnmarshalJSON([]byte) error
}
Unmarshaler is the interface implemented by types that can unmarshal a JSON
description of themselves. The input can be assumed to be a valid encoding
of a JSON value. UnmarshalJSON must copy the JSON data if it wishes to
retain the data after returning.
By convention, to approximate the behavior of Unmarshal itself, Unmarshalers
implement UnmarshalJSON([]byte("null")) as a no-op.
var _ Unmarshaler = (*RawMessage)(nil)
func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value)
indirect walks down v allocating pointers as needed, until it gets to a
non-pointer. If it encounters an Unmarshaler, indirect stops and returns
that. If decodingNull is true, indirect stops at the first settable pointer
so it can be set to nil.
type UnsupportedTypeError struct {
Type reflect.Type
}
An UnsupportedTypeError is returned by Marshal when attempting to encode an
unsupported value type.
func (e *UnsupportedTypeError) Error() string
type UnsupportedValueError struct {
Value reflect.Value
Str string
}
An UnsupportedValueError is returned by Marshal when attempting to encode an
unsupported value.
func (e *UnsupportedValueError) Error() string
type arrayEncoder struct {
elemEnc encoderFunc
}
func (ae arrayEncoder) encode(e *encodeState, v reflect.Value, opts encOpts)
type condAddrEncoder struct {
canAddrEnc, elseEnc encoderFunc
}
func (ce condAddrEncoder) encode(e *encodeState, v reflect.Value, opts encOpts)
type decodeState struct {
data []byte
scan scanner
errorContext *errorContext
savedError error
useNumber bool
disallowUnknownFields bool
}
decodeState represents the state while decoding a JSON value.
func (d *decodeState) addErrorContext(err error) error
addErrorContext returns a new error enhanced with information from
d.errorContext
func (d *decodeState) array(v reflect.Value) error
array consumes an array from d.data[d.off-1:], decoding into v. The first
byte of the array ('[') has been read already.
func (d *decodeState) arrayInterface() []any
arrayInterface is like array but returns []any.
func (d *decodeState) convertNumber(s string) (any, error)
convertNumber converts the number literal s to a float64 or a Number
depending on the setting of d.useNumber.
func (d *decodeState) init(data []byte) *decodeState
func (d *decodeState) literalInterface() any
literalInterface consumes and returns a literal from d.data[d.off-1:] and it
reads the following byte ahead. The first byte of the literal has been read
already (that's how the caller knows it's a literal).
func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) error
literalStore decodes a literal stored in item into v.
fromQuoted indicates whether this literal came from unwrapping a string from
the ",string" struct tag option. this is used only to produce more helpful
error messages.
func (d *decodeState) object(v reflect.Value) error
object consumes an object from d.data[d.off-1:], decoding into v. The first
byte ('{') of the object has been read already.
func (d *decodeState) objectInterface() map[string]any
objectInterface is like object but returns map[string]any.
func (d *decodeState) readIndex() int
readIndex returns the position of the last byte read.
func (d *decodeState) rescanLiteral()
rescanLiteral is similar to scanWhile(scanContinue), but it specialises
the common case where we're decoding a literal. The decoder scans the
input twice, once for syntax errors and to check the length of the value,
and the second to perform the decoding.
Only in the second step do we use decodeState to tokenize literals,
so we know there aren't any syntax errors. We can take advantage of that
knowledge, and scan a literal's bytes much more quickly.
func (d *decodeState) saveError(err error)
saveError saves the first err it is called with, for reporting at the end of
the unmarshal.
func (d *decodeState) scanNext()
scanNext processes the byte at d.data[d.off].
func (d *decodeState) scanWhile(op int)
scanWhile processes bytes in d.data[d.off:] until it receives a scan code
not equal to op.
func (d *decodeState) skip()
skip scans to the end of what was started.
func (d *decodeState) unmarshal(v any) error
func (d *decodeState) value(v reflect.Value) error
value consumes a JSON value from d.data[d.off-1:], decoding into v,
and reads the following byte ahead. If v is invalid, the value is discarded.
The first byte of the value has been read already.
func (d *decodeState) valueInterface() (val any)
valueInterface is like value but returns any.
func (d *decodeState) valueQuoted() any
valueQuoted is like value but decodes a quoted string literal or literal
null into an interface value. If it finds anything other than a quoted
string literal or null, valueQuoted returns unquotedValue{}.
type encOpts struct {
quoted bool
escapeHTML bool
}
type encodeState struct {
ptrLevel uint
ptrSeen map[any]struct{}
}
An encodeState encodes JSON into a bytes.Buffer.
func newEncodeState() *encodeState
func (e *encodeState) error(err error)
error aborts the encoding by panicking with err wrapped in jsonError.
func (e *encodeState) marshal(v any, opts encOpts) (err error)
func (e *encodeState) reflectValue(v reflect.Value, opts encOpts)
type encoderFunc func(e *encodeState, v reflect.Value, opts encOpts)
func newArrayEncoder(t reflect.Type) encoderFunc
func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc
newCondAddrEncoder returns an encoder that checks whether its value CanAddr
and delegates to canAddrEnc if so, else to elseEnc.
func newMapEncoder(t reflect.Type) encoderFunc
func newPtrEncoder(t reflect.Type) encoderFunc
func newSliceEncoder(t reflect.Type) encoderFunc
func newStructEncoder(t reflect.Type) encoderFunc
func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc
newTypeEncoder constructs an encoderFunc for a type. The returned encoder
only checks CanAddr when allowAddr is true.
func typeEncoder(t reflect.Type) encoderFunc
func valueEncoder(v reflect.Value) encoderFunc
type errorContext struct {
Struct reflect.Type
FieldStack []string
}
An errorContext provides context for type errors during decoding.
type field struct {
name string
tag bool
index []int
typ reflect.Type
omitEmpty bool
omitZero bool
isZero func(reflect.Value) bool
quoted bool
encoder encoderFunc
}
A field represents a single field found in a struct.
func dominantField(fields []field) (field, bool)
dominantField looks through the fields, all of which are known to have
the same name, to find the single field that dominates the others using
Go's embedding rules, modified by the presence of JSON tags. If there are
multiple top-level fields, the boolean will be false: This condition is an
error in Go and we skip all the fields.
func (bits floatEncoder) encode(e *encodeState, v reflect.Value, opts encOpts)
type isZeroer interface {
IsZero() bool
}
type jsonError struct{ error }
jsonError is an error wrapper type for internal use only. Panics with errors
are wrapped in jsonError so that the top-level recover can distinguish
intentional panics from this package.
type mapEncoder struct {
elemEnc encoderFunc
}
func (me mapEncoder) encode(e *encodeState, v reflect.Value, opts encOpts)
type ptrEncoder struct {
elemEnc encoderFunc
}
func (pe ptrEncoder) encode(e *encodeState, v reflect.Value, opts encOpts)
type reflectWithString struct {
v reflect.Value
ks string
}
type scanner struct {
step func(*scanner, byte) int
endTop bool
parseState []int
err error
bytes int64
}
A scanner is a JSON scanning state machine. Callers call scan.reset and then
pass bytes in one at a time by calling scan.step(&scan, c) for each byte.
The return value, referred to as an opcode, tells the caller about
significant parsing events like beginning and ending literals, objects, and
arrays, so that the caller can follow along if it wishes. The return value
scanEnd indicates that a single top-level JSON value has been completed,
*before* the byte that just got passed in. (The indication must be delayed
in order to recognize the end of numbers: is 123 a whole value or the
beginning of 12345e+6?).
func newScanner() *scanner
func (s *scanner) eof() int
eof tells the scanner that the end of input has been reached. It returns a
scan status just as s.step does.
func (s *scanner) error(c byte, context string) int
error records an error and switches to the error state.
func (s *scanner) popParseState()
popParseState pops a parse state (already obtained) off the stack and
updates s.step accordingly.
func (s *scanner) pushParseState(c byte, newParseState int, successState int) int
pushParseState pushes a new parse state p onto the parse stack. an error
state is returned if maxNestingDepth was exceeded, otherwise successState is
returned.
func (s *scanner) reset()
reset prepares the scanner for use. It must be called before calling s.step.
type sliceEncoder struct {
arrayEnc encoderFunc
}
sliceEncoder just wraps an arrayEncoder, checking to make sure the value
isn't nil.
func (se sliceEncoder) encode(e *encodeState, v reflect.Value, opts encOpts)
type structEncoder struct {
fields structFields
}
func (se structEncoder) encode(e *encodeState, v reflect.Value, opts encOpts)
type structFields struct {
list []field
byExactName map[string]*field
byFoldedName map[string]*field
}
func cachedTypeFields(t reflect.Type) structFields
cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
func typeFields(t reflect.Type) structFields
typeFields returns a list of fields that JSON should recognize for the
given type. The algorithm is breadth-first search over the set of structs to
include - the top struct and then any reachable anonymous structs.
typeFields should be an internal detail, but widely used packages access it
using linkname. Notable members of the hall of shame include:
- github.com/bytedance/sonic
Do not remove or change the type signature. See go.dev/issue/67401.
type tagOptions string
tagOptions is the string following a comma in a struct field's "json" tag,
or the empty string. It does not include the leading comma.
func parseTag(tag string) (string, tagOptions)
parseTag splits a struct field's json tag into its name and comma-separated
options.
func (o tagOptions) Contains(optionName string) bool
Contains reports whether a comma-separated list of options contains a
particular substr flag. substr must be surrounded by a string boundary or
commas.
type unquotedValue struct{}
encoding/pem
func Encode(out io.Writer, b *Block) error
Encode writes the PEM encoding of b to out.
func EncodeToMemory(b *Block) []byte
EncodeToMemory returns the PEM encoding of b.
If b has invalid headers and cannot be encoded, EncodeToMemory returns nil.
If it is important to report details about this error case, use Encode
instead.
func getLine(data []byte) (line, rest []byte)
getLine results the first \r\n or \n delineated line from the given byte
array. The line does not include trailing whitespace or the trailing new
line bytes. The remainder of the byte array (also not including the new line
bytes) is also returned and this will always be smaller than the original
argument.
func removeSpacesAndTabs(data []byte) []byte
removeSpacesAndTabs returns a copy of its input with all spaces and tabs
removed, if there were any. Otherwise, the input is returned unchanged.
The base64 decoder already skips newline characters, so we don't need to
filter them out here.
func writeHeader(out io.Writer, k, v string) error
TYPES
type Block struct {
}
A Block represents a PEM encoded structure.
The encoded form is:
-----BEGIN Type-----
Headers
base64-encoded Bytes
-----END Type-----
where [Block.Headers] is a possibly empty sequence of Key: Value lines.
func Decode(data []byte) (p *Block, rest []byte)
Decode will find the next PEM formatted block (certificate, private key etc)
in the input. It returns that block and the remainder of the input. If no
PEM data is found, p is nil and the whole of the input is returned in rest.
type lineBreaker struct {
line [pemLineLength]byte
used int
out io.Writer
}
func (l *lineBreaker) Close() (err error)
func (l *lineBreaker) Write(b []byte) (n int, err error)
encoding/xml
func Escape(w io.Writer, s []byte)
Escape is like EscapeText but omits the error return value. It is provided
for backwards compatibility with Go 1.0. Code targeting Go 1.1 or later
should use EscapeText.
func EscapeText(w io.Writer, s []byte) error
EscapeText writes to w the properly escaped XML equivalent of the plain text
data s.
func Marshal(v any) ([]byte, error)
Marshal returns the XML encoding of v.
Marshal handles an array or slice by marshaling each of the elements.
Marshal handles a pointer by marshaling the value it points at or,
if the pointer is nil, by writing nothing. Marshal handles an interface
value by marshaling the value it contains or, if the interface value is nil,
by writing nothing. Marshal handles all other data by writing one or more
XML elements containing the data.
The name for the XML elements is taken from, in order of preference:
- the tag on the XMLName field, if the data is a struct
- the value of the XMLName field of type Name
- the tag of the struct field used to obtain the data
- the name of the struct field used to obtain the data
- the name of the marshaled type
The XML element for a struct contains marshaled elements for each of the
exported fields of the struct, with these exceptions:
- the XMLName field, described above, is omitted.
- a field with tag "-" is omitted.
- a field with tag "name,attr" becomes an attribute with the given name in
the XML element.
- a field with tag ",attr" becomes an attribute with the field name in the
XML element.
- a field with tag ",chardata" is written as character data, not as an XML
element.
- a field with tag ",cdata" is written as character data wrapped in one or
more <![CDATA[ ... ]]> tags, not as an XML element.
- a field with tag ",innerxml" is written verbatim, not subject to the
usual marshaling procedure.
- a field with tag ",comment" is written as an XML comment, not subject
to the usual marshaling procedure. It must not contain the "--" string
within it.
- a field with a tag including the "omitempty" option is omitted if the
field value is empty. The empty values are false, 0, any nil pointer or
interface value, and any array, slice, map, or string of length zero.
- an anonymous struct field is handled as if the fields of its value were
part of the outer struct.
- an anonymous struct field of interface type is treated the same as
having that type as its name, rather than being anonymous.
- a field implementing Marshaler is written by calling its MarshalXML
method.
- a field implementing encoding.TextMarshaler is written by encoding the
result of its MarshalText method as text.
If a field uses a tag "a>b>c", then the element c will be nested inside
parent elements a and b. Fields that appear next to each other that name the
same parent will be enclosed in one XML element.
If the XML name for a struct field is defined by both the field tag and the
struct's XMLName field, the names must match.
See MarshalIndent for an example.
Marshal will return an error if asked to marshal a channel, function,
or map.
func MarshalIndent(v any, prefix, indent string) ([]byte, error)
MarshalIndent works like Marshal, but each XML element begins on a new
indented line that starts with prefix and is followed by one or more copies
of indent according to the nesting depth.
func Unmarshal(data []byte, v any) error
Unmarshal parses the XML-encoded data and stores the result in the value
pointed to by v, which must be an arbitrary struct, slice, or string.
Well-formed data that does not fit into v is discarded.
Because Unmarshal uses the reflect package, it can only assign to exported
(upper case) fields. Unmarshal uses a case-sensitive comparison to match XML
element names to tag values and struct field names.
Unmarshal maps an XML element to a struct using the following rules.
In the rules, the tag of a field refers to the value associated with the key
'xml' in the struct field's tag (see the example above).
- If the struct has a field of type []byte or string with tag ",innerxml",
Unmarshal accumulates the raw XML nested inside the element in that
field. The rest of the rules still apply.
- If the struct has a field named XMLName of type Name, Unmarshal records
the element name in that field.
- If the XMLName field has an associated tag of the form "name" or
"namespace-URL name", the XML element must have the given name (and,
optionally, name space) or else Unmarshal returns an error.
- If the XML element has an attribute whose name matches a struct field
name with an associated tag containing ",attr" or the explicit name
in a struct field tag of the form "name,attr", Unmarshal records the
attribute value in that field.
- If the XML element has an attribute not handled by the previous rule and
the struct has a field with an associated tag containing ",any,attr",
Unmarshal records the attribute value in the first such field.
- If the XML element contains character data, that data is accumulated in
the first struct field that has tag ",chardata". The struct field may
have type []byte or string. If there is no such field, the character
data is discarded.
- If the XML element contains comments, they are accumulated in the first
struct field that has tag ",comment". The struct field may have type
[]byte or string. If there is no such field, the comments are discarded.
- If the XML element contains a sub-element whose name matches the prefix
of a tag formatted as "a" or "a>b>c", unmarshal will descend into the
XML structure looking for elements with the given names, and will map
the innermost elements to that struct field. A tag starting with ">" is
equivalent to one starting with the field name followed by ">".
- If the XML element contains a sub-element whose name matches a struct
field's XMLName tag and the struct field has no explicit name tag as per
the previous rule, unmarshal maps the sub-element to that struct field.
- If the XML element contains a sub-element whose name matches a field
without any mode flags (",attr", ",chardata", etc), Unmarshal maps the
sub-element to that struct field.
- If the XML element contains a sub-element that hasn't matched any of the
above rules and the struct has a field with tag ",any", unmarshal maps
the sub-element to that struct field.
- An anonymous struct field is handled as if the fields of its value were
part of the outer struct.
- A struct field with tag "-" is never unmarshaled into.
If Unmarshal encounters a field type that implements the Unmarshaler
interface, Unmarshal calls its UnmarshalXML method to produce the
value from the XML element. Otherwise, if the value implements
encoding.TextUnmarshaler, Unmarshal calls that value's UnmarshalText method.
Unmarshal maps an XML element to a string or []byte by saving the
concatenation of that element's character data in the string or []byte.
The saved []byte is never nil.
Unmarshal maps an attribute value to a string or []byte by saving the value
in the string or slice.
Unmarshal maps an attribute value to an Attr by saving the attribute,
including its name, in the Attr.
Unmarshal maps an XML element or attribute value to a slice by extending
the length of the slice and mapping the element or attribute to the newly
created value.
Unmarshal maps an XML element or attribute value to a bool by setting it
to the boolean value represented by the string. Whitespace is trimmed and
ignored.
Unmarshal maps an XML element or attribute value to an integer or
floating-point field by setting the field to the result of interpreting
the string value in decimal. There is no check for overflow. Whitespace is
trimmed and ignored.
Unmarshal maps an XML element to a Name by recording the element name.
Unmarshal maps an XML element to a pointer by setting the pointer to a
freshly allocated value and then mapping the element to that value.
A missing element or empty attribute value will be unmarshaled as a zero
value. If the field is a slice, a zero value will be appended to the field.
Otherwise, the field will be set to its zero value.
func addFieldInfo(typ reflect.Type, tinfo *typeInfo, newf *fieldInfo) error
addFieldInfo adds finfo to tinfo.fields if there are no conflicts,
or if conflicts arise from previous fields that were obtained from deeper
embedded structures than finfo. In the latter case, the conflicting entries
are dropped. A conflict occurs when the path (parent + name) to a field is
itself a prefix of another path, or when two paths match exactly. It is okay
for field paths to share a common, shorter prefix.
func copyValue(dst reflect.Value, src []byte) (err error)
func emitCDATA(w io.Writer, s []byte) error
emitCDATA writes to w the CDATA-wrapped plain text data s. It escapes CDATA
directives nested in s.
func escapeText(w io.Writer, s []byte, escapeNewline bool) error
escapeText writes to w the properly escaped XML equivalent of the plain text
data s. If escapeNewline is true, newline characters will be escaped.
func indirect(vf reflect.Value) reflect.Value
indirect drills into interfaces and pointers, returning the pointed-at
value. If it encounters a nil interface or pointer, indirect returns that
nil value. This can turn into an infinite loop given a cyclic chain,
but it matches the Go 1 behavior.
func isEmptyValue(v reflect.Value) bool
func isInCharacterRange(r rune) (inrange bool)
Decide whether the given rune is in the XML Character Range, per the Char
func isName(s []byte) bool
func isNameByte(c byte) bool
func isNameString(s string) bool
func isValidDirective(dir Directive) bool
isValidDirective reports whether dir is a valid directive text, meaning
angle brackets are matched, ignoring comments and strings.
func procInst(param, s string) string
procInst parses the `param="..."` or `param='...'` value out of the provided
string, returning "" if not found.
func receiverType(val any) string
receiverType returns the receiver type to use in an expression like
"%s.MethodName".
TYPES
type Attr struct {
Name Name
Value string
}
An Attr represents an attribute in an XML element (Name=Value).
type CharData []byte
A CharData represents XML character data (raw text), in which XML escape
sequences have been replaced by the characters they represent.
func (c CharData) Copy() CharData
Copy creates a new copy of CharData.
type Comment []byte
A Comment represents an XML comment of the form <!--comment-->. The bytes do
not include the <!-- and --> comment markers.
func (c Comment) Copy() Comment
Copy creates a new copy of Comment.
type Decoder struct {
Strict bool
AutoClose []string
Entity map[string]string
CharsetReader func(charset string, input io.Reader) (io.Reader, error)
DefaultSpace string
r io.ByteReader
t TokenReader
buf bytes.Buffer
saved *bytes.Buffer
stk *stack
free *stack
needClose bool
toClose Name
nextToken Token
nextByte int
ns map[string]string
err error
line int
linestart int64
offset int64
unmarshalDepth int
}
A Decoder represents an XML parser reading a particular input stream.
The parser assumes that its input is encoded in UTF-8.
func NewDecoder(r io.Reader) *Decoder
NewDecoder creates a new XML parser reading from r. If r does not implement
io.ByteReader, NewDecoder will do its own buffering.
func NewTokenDecoder(t TokenReader) *Decoder
NewTokenDecoder creates a new XML parser using an underlying token stream.
func (d *Decoder) Decode(v any) error
Decode works like Unmarshal, except it reads the decoder stream to find the
start element.
func (d *Decoder) DecodeElement(v any, start *StartElement) error
DecodeElement works like Unmarshal except that it takes a pointer to the
start XML element to decode into v. It is useful when a client reads
some raw XML tokens itself but also wants to defer to Unmarshal for some
elements.
func (d *Decoder) InputOffset() int64
InputOffset returns the input stream byte offset of the current decoder
position. The offset gives the location of the end of the most recently
returned token and the beginning of the next token.
func (d *Decoder) InputPos() (line, column int)
InputPos returns the line of the current decoder position and the 1 based
input position of the line. The position gives the location of the end of
the most recently returned token.
func (d *Decoder) RawToken() (Token, error)
RawToken is like Decoder.Token but does not verify that start and end
elements match and does not translate name space prefixes to their
corresponding URLs.
func (d *Decoder) Skip() error
Skip reads tokens until it has consumed the end element matching the
most recent start element already consumed, skipping nested structures.
It returns nil if it finds an end element matching the start element;
otherwise it returns an error describing the problem.
func (d *Decoder) Token() (Token, error)
Token returns the next XML token in the input stream. At the end of the
input stream, Token returns nil, io.EOF.
Slices of bytes in the returned token data refer to the parser's internal
buffer and remain valid only until the next call to Token. To acquire a copy
of the bytes, call CopyToken or the token's Copy method.
Token expands self-closing elements such as <br> into separate start and end
elements returned by successive calls.
Token guarantees that the StartElement and EndElement tokens it returns are
properly nested and matched: if Token encounters an unexpected end element
or EOF before all expected end elements, it will return an error.
If [Decoder.CharsetReader] is called and returns an error, the error is
wrapped and returned.
Token implements XML name spaces as described by
in the Token has the Space set to the URL identifying its name space when
known. If Token encounters an unrecognized name space prefix, it uses the
prefix as the Space rather than report an error.
func (d *Decoder) attrval() []byte
func (d *Decoder) autoClose(t Token) (Token, bool)
If the top element on the stack is autoclosing and t is not the end tag,
invent the end tag.
func (d *Decoder) getc() (b byte, ok bool)
Read a single byte. If there is no byte to read, return ok==false and leave
the error in d.err. Maintain line number.
func (d *Decoder) mustgetc() (b byte, ok bool)
Must read a single byte. If there is no byte to read, set d.err to
SyntaxError("unexpected EOF") and return ok==false
func (d *Decoder) name() (s string, ok bool)
Get name: /first(first|second)*/ Do not set d.err if the name is missing
(unless unexpected EOF is received): let the caller provide better context.
func (d *Decoder) nsname() (name Name, ok bool)
Get name space name: name with a : stuck in the middle. The part before the
: is the name space identifier.
func (d *Decoder) pop() *stack
func (d *Decoder) popEOF() bool
Undo a pushEOF. The element must have been finished, so the EOF should be at
the top of the stack.
func (d *Decoder) popElement(t *EndElement) bool
Record that we are ending an element with the given name. The name must
match the record at the top of the stack, which must be a pushElement
record. After popping the element, apply any undo records from the stack to
restore the name translations that existed before we saw this element.
func (d *Decoder) push(kind int) *stack
func (d *Decoder) pushEOF()
Record that after the current element is finished (that element is already
pushed on the stack) Token should return EOF until popEOF is called.
func (d *Decoder) pushElement(name Name)
Record that we are starting an element with the given name.
func (d *Decoder) pushNs(local string, url string, ok bool)
Record that we are changing the value of ns[local]. The old value is url,
ok.
func (d *Decoder) rawToken() (Token, error)
func (d *Decoder) readName() (ok bool)
Read a name and append its bytes to d.buf. The name is delimited by any
single-byte character not valid in names. All multi-byte characters are
accepted; the caller must check their validity.
func (d *Decoder) savedOffset() int
Return saved offset. If we did ungetc (nextByte >= 0), have to back up one.
func (d *Decoder) space()
Skip spaces if any
func (d *Decoder) switchToReader(r io.Reader)
func (d *Decoder) syntaxError(msg string) error
Creates a SyntaxError with the current line number.
func (d *Decoder) text(quote int, cdata bool) []byte
Read plain text section (XML calls it character data). If quote >= 0, we are
in a quoted string and need to find the matching quote. If cdata == true,
we are in a <![CDATA[ section and need to find ]]>. On failure return nil
and leave the error in d.err.
func (d *Decoder) translate(n *Name, isElementName bool)
Apply name space translation to name n. The default name space (for
Space=="") applies only to element names, not to attribute names.
func (d *Decoder) ungetc(b byte)
Unread a single byte.
func (d *Decoder) unmarshal(val reflect.Value, start *StartElement, depth int) error
Unmarshal a single XML element into val.
func (d *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error
unmarshalAttr unmarshals a single XML attribute into val.
func (d *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error
unmarshalInterface unmarshals a single XML element into val. start is the
opening tag of the element.
func (d *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement, depth int) (consumed bool, err error)
unmarshalPath walks down an XML structure looking for wanted paths,
and calls unmarshal on them. The consumed result tells whether XML elements
have been consumed from the Decoder until start's matching end element,
or if it's still untouched because start is uninteresting for sv's fields.
func (d *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler) error
unmarshalTextInterface unmarshals a single XML element into val. The
chardata contained in the element (but not its children) is passed to the
text unmarshaler.
type Directive []byte
A Directive represents an XML directive of the form <!text>. The bytes do
not include the <! and > markers.
func (d Directive) Copy() Directive
Copy creates a new copy of Directive.
type Encoder struct {
p printer
}
An Encoder writes XML data to an output stream.
func NewEncoder(w io.Writer) *Encoder
NewEncoder returns a new encoder that writes to w.
func (enc *Encoder) Close() error
Close the Encoder, indicating that no more data will be written. It flushes
any buffered XML to the underlying writer and returns an error if the
written XML is invalid (e.g. by containing unclosed elements).
func (enc *Encoder) Encode(v any) error
Encode writes the XML encoding of v to the stream.
See the documentation for Marshal for details about the conversion of Go
values to XML.
Encode calls Encoder.Flush before returning.
func (enc *Encoder) EncodeElement(v any, start StartElement) error
EncodeElement writes the XML encoding of v to the stream, using start as the
outermost tag in the encoding.
See the documentation for Marshal for details about the conversion of Go
values to XML.
EncodeElement calls Encoder.Flush before returning.
func (enc *Encoder) EncodeToken(t Token) error
EncodeToken writes the given XML token to the stream. It returns an error if
StartElement and EndElement tokens are not properly matched.
EncodeToken does not call Encoder.Flush, because usually it is part of
a larger operation such as Encoder.Encode or Encoder.EncodeElement (or
a custom Marshaler's MarshalXML invoked during those), and those will
call Flush when finished. Callers that create an Encoder and then invoke
EncodeToken directly, without using Encode or EncodeElement, need to call
Flush when finished to ensure that the XML is written to the underlying
writer.
EncodeToken allows writing a ProcInst with Target set to "xml" only as the
first token in the stream.
func (enc *Encoder) Flush() error
Flush flushes any buffered XML to the underlying writer. See the
Encoder.EncodeToken documentation for details about when it is necessary.
func (enc *Encoder) Indent(prefix, indent string)
Indent sets the encoder to generate XML in which each element begins on a
new indented line that starts with prefix and is followed by one or more
copies of indent according to the nesting depth.
type EndElement struct {
Name Name
}
An EndElement represents an XML end element.
type Marshaler interface {
MarshalXML(e *Encoder, start StartElement) error
}
Marshaler is the interface implemented by objects that can marshal
themselves into valid XML elements.
MarshalXML encodes the receiver as zero or more XML elements. By convention,
arrays or slices are typically encoded as a sequence of elements, one per
entry. Using start as the element tag is not required, but doing so will
enable Unmarshal to match the XML elements to the correct struct field.
One common implementation strategy is to construct a separate value with
a layout corresponding to the desired XML and then to encode it using
e.EncodeElement. Another common strategy is to use repeated calls to
e.EncodeToken to generate the XML output one token at a time. The sequence
of encoded tokens must make up zero or more valid XML elements.
type MarshalerAttr interface {
MarshalXMLAttr(name Name) (Attr, error)
}
MarshalerAttr is the interface implemented by objects that can marshal
themselves into valid XML attributes.
MarshalXMLAttr returns an XML attribute with the encoded value of the
receiver. Using name as the attribute name is not required, but doing so
will enable Unmarshal to match the attribute to the correct struct field.
If MarshalXMLAttr returns the zero attribute Attr{}, no attribute will be
generated in the output. MarshalXMLAttr is used only for struct fields with
the "attr" option in the field tag.
type Name struct {
Space, Local string
}
A Name represents an XML name (Local) annotated with a name space identifier
(Space). In tokens returned by Decoder.Token, the Space identifier is given
as a canonical URL, not the short prefix used in the document being parsed.
type ProcInst struct {
Target string
Inst []byte
}
A ProcInst represents an XML processing instruction of the form <?target
inst?>
func (p ProcInst) Copy() ProcInst
Copy creates a new copy of ProcInst.
type StartElement struct {
Name Name
Attr []Attr
}
A StartElement represents an XML start element.
func defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement
defaultStart returns the default start element to use, given the reflect
type, field info, and start template.
func (e StartElement) Copy() StartElement
Copy creates a new copy of StartElement.
func (e StartElement) End() EndElement
End returns the corresponding XML end element.
type SyntaxError struct {
Msg string
Line int
}
A SyntaxError represents a syntax error in the XML input stream.
func (e *SyntaxError) Error() string
type TagPathError struct {
Struct reflect.Type
Field1, Tag1 string
Field2, Tag2 string
}
A TagPathError represents an error in the unmarshaling process caused by the
use of field tags with conflicting paths.
func (e *TagPathError) Error() string
type Token any
A Token is an interface holding one of the token types: StartElement,
EndElement, CharData, Comment, ProcInst, or Directive.
func CopyToken(t Token) Token
CopyToken returns a copy of a Token.
type TokenReader interface {
Token() (Token, error)
}
A TokenReader is anything that can decode a stream of XML tokens, including
a Decoder.
When Token encounters an error or end-of-file condition after successfully
reading a token, it returns the token. It may return the (non-nil) error
from the same call or return the error (and a nil token) from a subsequent
call. An instance of this general case is that a TokenReader returning a
non-nil token at the end of the token stream may return either io.EOF or a
nil error. The next Read should return nil, io.EOF.
Implementations of Token are discouraged from returning a nil token with
a nil error. Callers should treat a return of nil, nil as indicating that
nothing happened; in particular it does not indicate EOF.
type UnmarshalError string
An UnmarshalError represents an error in the unmarshaling process.
func (e UnmarshalError) Error() string
type Unmarshaler interface {
UnmarshalXML(d *Decoder, start StartElement) error
}
Unmarshaler is the interface implemented by objects that can unmarshal an
XML element description of themselves.
UnmarshalXML decodes a single XML element beginning with the given start
element. If it returns an error, the outer call to Unmarshal stops and
returns that error. UnmarshalXML must consume exactly one XML element.
One common implementation strategy is to unmarshal into a separate value
with a layout matching the expected XML using d.DecodeElement, and then to
copy the data from that value into the receiver. Another common strategy is
to use d.Token to process the XML object one token at a time. UnmarshalXML
may not use d.RawToken.
type UnmarshalerAttr interface {
UnmarshalXMLAttr(attr Attr) error
}
UnmarshalerAttr is the interface implemented by objects that can unmarshal
an XML attribute description of themselves.
UnmarshalXMLAttr decodes a single XML attribute. If it returns an error,
the outer call to Unmarshal stops and returns that error. UnmarshalXMLAttr
is used only for struct fields with the "attr" option in the field tag.
type UnsupportedTypeError struct {
Type reflect.Type
}
UnsupportedTypeError is returned when Marshal encounters a type that cannot
be converted into XML.
func (e *UnsupportedTypeError) Error() string
type fieldFlags int
const (
fElement fieldFlags = 1 << iota
fAttr
fCDATA
fCharData
fInnerXML
fComment
fAny
fOmitEmpty
fMode = fElement | fAttr | fCDATA | fCharData | fInnerXML | fComment | fAny
xmlName = "XMLName"
)
type fieldInfo struct {
idx []int
name string
xmlns string
flags fieldFlags
parents []string
}
fieldInfo holds details for the xml representation of a single field.
func lookupXMLName(typ reflect.Type) (xmlname *fieldInfo)
lookupXMLName returns the fieldInfo for typ's XMLName field in case it
exists and has a valid xml field tag, otherwise it returns nil.
func structFieldInfo(typ reflect.Type, f *reflect.StructField) (*fieldInfo, error)
structFieldInfo builds and returns a fieldInfo for f.
func (finfo *fieldInfo) value(v reflect.Value, shouldInitNilPointers bool) reflect.Value
value returns v's field value corresponding to finfo. It's equivalent to
v.FieldByIndex(finfo.idx), but when passed initNilPointers, it initializes
and dereferences pointers as necessary. When passed dontInitNilPointers and
a nil pointer is reached, the function returns a zero reflect.Value.
type parentStack struct {
p *printer
stack []string
}
func (s *parentStack) push(parents []string) error
push adds parent elements to the stack and writes open tags.
func (s *parentStack) trim(parents []string) error
trim updates the XML context to match the longest common prefix of the
stack and the given parents. A closing tag will be written for every parent
popped. Passing a zero slice or nil will close all the elements.
type printer struct {
w *bufio.Writer
encoder *Encoder
seq int
indent string
prefix string
depth int
indentedIn bool
putNewline bool
prefixes []string
tags []Name
closed bool
err error
}
func (p *printer) Close() error
Close the Encoder, indicating that no more data will be written. It flushes
any buffered XML to the underlying writer and returns an error if the
written XML is invalid (e.g. by containing unclosed elements).
func (p *printer) EscapeString(s string)
EscapeString writes to p the properly escaped XML equivalent of the plain
text data s.
func (p *printer) Write(b []byte) (n int, err error)
Write implements io.Writer
func (p *printer) WriteByte(c byte) error
WriteByte implements io.ByteWriter
func (p *printer) WriteString(s string) (n int, err error)
WriteString implements io.StringWriter
func (p *printer) cachedWriteError() error
return the bufio Writer's cached write error
func (p *printer) createAttrPrefix(url string) string
createAttrPrefix finds the name space prefix attribute to use for the given
name space, defining a new prefix if necessary. It returns the prefix.
func (p *printer) deleteAttrPrefix(prefix string)
deleteAttrPrefix removes an attribute name space prefix.
func (p *printer) markPrefix()
func (p *printer) marshalAttr(start *StartElement, name Name, val reflect.Value) error
marshalAttr marshals an attribute with the given name and value, adding to
start.Attr.
func (p *printer) marshalInterface(val Marshaler, start StartElement) error
marshalInterface marshals a Marshaler interface value.
func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error)
func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error
func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error
marshalTextInterface marshals a TextMarshaler interface value.
func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error
marshalValue writes one or more XML elements representing val. If val was
obtained from a struct field, finfo must have its details.
func (p *printer) popPrefix()
func (p *printer) writeEnd(name Name) error
func (p *printer) writeIndent(depthDelta int)
func (p *printer) writeStart(start *StartElement) error
writeStart writes the given start element.
type stack struct {
next *stack
kind int
name Name
ok bool
}
Parsing state - stack holds old name space translations and the current
set of open elements. The translations to pop when ending a given tag are
*below* it on the stack, which is more work but forced on us by XML.
type typeInfo struct {
xmlname *fieldInfo
fields []fieldInfo
}
typeInfo holds details for the xml representation of a type.
func getTypeInfo(typ reflect.Type) (*typeInfo, error)
getTypeInfo returns the typeInfo structure with details necessary for
marshaling and unmarshaling typ.
BUG: Mapping between XML elements and data structures is inherently flawed:
an XML element is an order-dependent collection of anonymous
values, while a data structure is an order-independent collection
of named values.
See [encoding/json] for a textual representation more suitable
to data structures.
errors
func As(err error, target any) bool
As finds the first error in err's tree that matches target, and if one
is found, sets target to that error value and returns true. Otherwise,
it returns false.
The tree consists of err itself, followed by the errors obtained by
repeatedly calling its Unwrap() error or Unwrap() []error method. When err
wraps multiple errors, As examines err followed by a depth-first traversal
of its children.
An error matches target if the error's concrete value is assignable to
the value pointed to by target, or if the error has a method As(any) bool
such that As(target) returns true. In the latter case, the As method is
responsible for setting target.
An error type might provide an As method so it can be treated as if it were
a different error type.
As panics if target is not a non-nil pointer to either a type that
implements error, or to any interface type.
func Is(err, target error) bool
Is reports whether any error in err's tree matches target.
The tree consists of err itself, followed by the errors obtained by
repeatedly calling its Unwrap() error or Unwrap() []error method. When err
wraps multiple errors, Is examines err followed by a depth-first traversal
of its children.
An error is considered to match a target if it is equal to that target or if
it implements a method Is(error) bool such that Is(target) returns true.
An error type might provide an Is method so it can be treated as equivalent
to an existing error. For example, if MyError defines
func (m MyError) Is(target error) bool { return target == fs.ErrExist }
then Is(MyError{}, fs.ErrExist) returns true. See syscall.Errno.Is for an
example in the standard library. An Is method should only shallowly compare
err and the target and not call Unwrap on either.
func Join(errs ...error) error
Join returns an error that wraps the given errors. Any nil error values are
discarded. Join returns nil if every value in errs is nil. The error formats
as the concatenation of the strings obtained by calling the Error method of
each element of errs, with a newline between each string.
A non-nil error returned by Join implements the Unwrap() []error method.
func New(text string) error
New returns an error that formats as the given text. Each call to New
returns a distinct error value even if the text is identical.
func Unwrap(err error) error
Unwrap returns the result of calling the Unwrap method on err, if err's type
contains an Unwrap method returning error. Otherwise, Unwrap returns nil.
Unwrap only calls a method of the form "Unwrap() error". In particular
Unwrap does not unwrap errors returned by Join.
func as(err error, target any, targetVal reflectlite.Value, targetType reflectlite.Type) bool
func is(err, target error, targetComparable bool) bool
TYPES
type errorString struct {
s string
}
errorString is a trivial implementation of error.
func (e *errorString) Error() string
type joinError struct {
errs []error
}
func (e *joinError) Error() string
func (e *joinError) Unwrap() []error
expvar
func Do(f func(KeyValue))
Do calls f for each exported variable. The global variable map is locked
during the iteration, but existing entries may be concurrently updated.
func Handler() http.Handler
Handler returns the expvar HTTP Handler.
This is only needed to install the handler in a non-standard location.
func Publish(name string, v Var)
Publish declares a named exported variable. This should be called from a
package's init function when it creates its Vars. If the name is already
registered then this will log.Panic.
func appendJSONQuote(b []byte, s string) []byte
TODO: Use json.appendString instead.
func cmdline() any
func expvarHandler(w http.ResponseWriter, r *http.Request)
func init()
func memstats() any
TYPES
type Float struct {
f atomic.Uint64
}
Float is a 64-bit float variable that satisfies the Var interface.
func NewFloat(name string) *Float
func (v *Float) Add(delta float64)
Add adds delta to v.
func (v *Float) Set(value float64)
Set sets v to value.
func (v *Float) String() string
func (v *Float) Value() float64
func (v *Float) appendJSON(b []byte) []byte
type Func func() any
Func implements Var by calling the function and formatting the returned
value using JSON.
func (f Func) String() string
func (f Func) Value() any
type Int struct {
i atomic.Int64
}
Int is a 64-bit integer variable that satisfies the Var interface.
func NewInt(name string) *Int
func (v *Int) Add(delta int64)
func (v *Int) Set(value int64)
func (v *Int) String() string
func (v *Int) Value() int64
func (v *Int) appendJSON(b []byte) []byte
type KeyValue struct {
Key string
Value Var
}
KeyValue represents a single entry in a Map.
type Map struct {
keysMu sync.RWMutex
}
Map is a string-to-Var map variable that satisfies the Var interface.
var vars Map
All published variables.
func NewMap(name string) *Map
func (v *Map) Add(key string, delta int64)
Add adds delta to the *Int value stored under the given map key.
func (v *Map) AddFloat(key string, delta float64)
AddFloat adds delta to the *Float value stored under the given map key.
func (v *Map) Delete(key string)
Delete deletes the given key from the map.
func (v *Map) Do(f func(KeyValue))
Do calls f for each entry in the map. The map is locked during the
iteration, but existing entries may be concurrently updated.
func (v *Map) Get(key string) Var
func (v *Map) Init() *Map
Init removes all keys from the map.
func (v *Map) Set(key string, av Var)
func (v *Map) String() string
func (v *Map) addKey(key string)
addKey updates the sorted list of keys in v.keys.
func (v *Map) appendJSON(b []byte) []byte
func (v *Map) appendJSONMayExpand(b []byte, expand bool) []byte
type String struct {
}
String is a string variable, and satisfies the Var interface.
func NewString(name string) *String
func (v *String) Set(value string)
func (v *String) String() string
String implements the Var interface. To get the unquoted string use
String.Value.
func (v *String) Value() string
func (v *String) appendJSON(b []byte) []byte
type Var interface {
String() string
}
Var is an abstract type for all exported variables.
func Get(name string) Var
Get retrieves a named exported variable. It returns nil if the name has not
been registered.
type jsonVar interface {
appendJSON(b []byte) []byte
}
flag
func Arg(i int) string
Arg returns the i'th command-line argument. Arg(0) is the first remaining
argument after flags have been processed. Arg returns an empty string if the
requested element does not exist.
func Args() []string
Args returns the non-flag command-line arguments.
func Bool(name string, value bool, usage string) *bool
Bool defines a bool flag with specified name, default value, and usage
string. The return value is the address of a bool variable that stores the
value of the flag.
func BoolFunc(name, usage string, fn func(string) error)
BoolFunc defines a flag with the specified name and usage string without
requiring values. Each time the flag is seen, fn is called with the value of
the flag. If fn returns a non-nil error, it will be treated as a flag value
parsing error.
func BoolVar(p *bool, name string, value bool, usage string)
BoolVar defines a bool flag with specified name, default value, and usage
string. The argument p points to a bool variable in which to store the value
of the flag.
func Duration(name string, value time.Duration, usage string) *time.Duration
Duration defines a time.Duration flag with specified name, default value,
and usage string. The return value is the address of a time.Duration
variable that stores the value of the flag. The flag accepts a value
acceptable to time.ParseDuration.
func DurationVar(p *time.Duration, name string, value time.Duration, usage string)
DurationVar defines a time.Duration flag with specified name, default value,
and usage string. The argument p points to a time.Duration variable in
which to store the value of the flag. The flag accepts a value acceptable to
time.ParseDuration.
func Float64(name string, value float64, usage string) *float64
Float64 defines a float64 flag with specified name, default value, and usage
string. The return value is the address of a float64 variable that stores
the value of the flag.
func Float64Var(p *float64, name string, value float64, usage string)
Float64Var defines a float64 flag with specified name, default value,
and usage string. The argument p points to a float64 variable in which to
store the value of the flag.
func Func(name, usage string, fn func(string) error)
Func defines a flag with the specified name and usage string. Each time
the flag is seen, fn is called with the value of the flag. If fn returns a
non-nil error, it will be treated as a flag value parsing error.
func Int(name string, value int, usage string) *int
Int defines an int flag with specified name, default value, and usage
string. The return value is the address of an int variable that stores the
value of the flag.
func Int64(name string, value int64, usage string) *int64
Int64 defines an int64 flag with specified name, default value, and usage
string. The return value is the address of an int64 variable that stores the
value of the flag.
func Int64Var(p *int64, name string, value int64, usage string)
Int64Var defines an int64 flag with specified name, default value, and usage
string. The argument p points to an int64 variable in which to store the
value of the flag.
func IntVar(p *int, name string, value int, usage string)
IntVar defines an int flag with specified name, default value, and usage
string. The argument p points to an int variable in which to store the value
of the flag.
func NArg() int
NArg is the number of arguments remaining after flags have been processed.
func NFlag() int
NFlag returns the number of command-line flags that have been set.
func Parse()
Parse parses the command-line flags from os.Args[1:]. Must be called after
all flags are defined and before flags are accessed by the program.
func Parsed() bool
Parsed reports whether the command-line flags have been parsed.
func PrintDefaults()
PrintDefaults prints, to standard error unless configured otherwise, a usage
message showing the default settings of all defined command-line flags.
For an integer valued flag x, the default output has the form
-x int
usage-message-for-x (default 7)
The usage message will appear on a separate line for anything but a bool
flag with a one-byte name. For bool flags, the type is omitted and if
the flag name is one byte the usage message appears on the same line.
The parenthetical default is omitted if the default is the zero value for
the type. The listed type, here int, can be changed by placing a back-quoted
name in the flag's usage string; the first such item in the message is
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment