build(deps): bump the golang group with 5 updates

Bumps the golang group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [github.com/Microsoft/hcsshim](https://github.com/Microsoft/hcsshim) | `0.11.4` | `0.12.0` |
| [github.com/alexflint/go-filemutex](https://github.com/alexflint/go-filemutex) | `1.2.0` | `1.3.0` |
| [github.com/onsi/ginkgo/v2](https://github.com/onsi/ginkgo) | `2.13.2` | `2.16.0` |
| [github.com/onsi/gomega](https://github.com/onsi/gomega) | `1.30.0` | `1.31.1` |
| [golang.org/x/sys](https://github.com/golang/sys) | `0.15.0` | `0.17.0` |


Updates `github.com/Microsoft/hcsshim` from 0.11.4 to 0.12.0
- [Release notes](https://github.com/Microsoft/hcsshim/releases)
- [Commits](https://github.com/Microsoft/hcsshim/compare/v0.11.4...v0.12.0)

Updates `github.com/alexflint/go-filemutex` from 1.2.0 to 1.3.0
- [Release notes](https://github.com/alexflint/go-filemutex/releases)
- [Commits](https://github.com/alexflint/go-filemutex/compare/v1.2.0...v1.3.0)

Updates `github.com/onsi/ginkgo/v2` from 2.13.2 to 2.16.0
- [Release notes](https://github.com/onsi/ginkgo/releases)
- [Changelog](https://github.com/onsi/ginkgo/blob/master/CHANGELOG.md)
- [Commits](https://github.com/onsi/ginkgo/compare/v2.13.2...v2.16.0)

Updates `github.com/onsi/gomega` from 1.30.0 to 1.31.1
- [Release notes](https://github.com/onsi/gomega/releases)
- [Changelog](https://github.com/onsi/gomega/blob/master/CHANGELOG.md)
- [Commits](https://github.com/onsi/gomega/compare/v1.30.0...v1.31.1)

Updates `golang.org/x/sys` from 0.15.0 to 0.17.0
- [Commits](https://github.com/golang/sys/compare/v0.15.0...v0.17.0)

---
updated-dependencies:
- dependency-name: github.com/Microsoft/hcsshim
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang
- dependency-name: github.com/alexflint/go-filemutex
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang
- dependency-name: github.com/onsi/ginkgo/v2
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang
- dependency-name: github.com/onsi/gomega
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang
- dependency-name: golang.org/x/sys
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: golang
...

Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
dependabot[bot]
2024-03-11 15:54:46 +00:00
committed by GitHub
parent 0144de0fcf
commit 394ab0d149
376 changed files with 12902 additions and 33268 deletions

View File

@ -12,14 +12,16 @@ import (
"syscall"
"time"
"go.opencensus.io/trace"
"github.com/Microsoft/hcsshim/internal/cow"
hcsschema "github.com/Microsoft/hcsshim/internal/hcs/schema2"
"github.com/Microsoft/hcsshim/internal/log"
"github.com/Microsoft/hcsshim/internal/oc"
"github.com/Microsoft/hcsshim/internal/protocol/guestrequest"
"github.com/Microsoft/hcsshim/internal/vmcompute"
"go.opencensus.io/trace"
)
// ContainerError is an error encountered in HCS
type Process struct {
handleLock sync.RWMutex
handle vmcompute.HcsProcess
@ -50,35 +52,6 @@ func newProcess(process vmcompute.HcsProcess, processID int, computeSystem *Syst
}
}
type processModifyRequest struct {
Operation string
ConsoleSize *consoleSize `json:",omitempty"`
CloseHandle *closeHandle `json:",omitempty"`
}
type consoleSize struct {
Height uint16
Width uint16
}
type closeHandle struct {
Handle string
}
type processStatus struct {
ProcessID uint32
Exited bool
ExitCode uint32
LastWaitResult int32
}
const stdIn string = "StdIn"
const (
modifyConsoleSize string = "ConsoleSize"
modifyCloseHandle string = "CloseHandle"
)
// Pid returns the process ID of the process within the container.
func (process *Process) Pid() int {
return process.processID
@ -90,7 +63,7 @@ func (process *Process) SystemID() string {
}
func (process *Process) processSignalResult(ctx context.Context, err error) (bool, error) {
switch err {
switch err { //nolint:errorlint
case nil:
return true, nil
case ErrVmcomputeOperationInvalidState, ErrComputeSystemDoesNotExist, ErrElementNotFound:
@ -260,14 +233,14 @@ func (process *Process) waitBackground() {
process.handleLock.RLock()
defer process.handleLock.RUnlock()
// Make sure we didnt race with Close() here
// Make sure we didn't race with Close() here
if process.handle != 0 {
propertiesJSON, resultJSON, err = vmcompute.HcsGetProcessProperties(ctx, process.handle)
events := processHcsResult(ctx, resultJSON)
if err != nil {
err = makeProcessError(process, operation, err, events)
} else {
properties := &processStatus{}
properties := &hcsschema.ProcessStatus{}
err = json.Unmarshal([]byte(propertiesJSON), properties)
if err != nil {
err = makeProcessError(process, operation, err, nil)
@ -318,10 +291,9 @@ func (process *Process) ResizeConsole(ctx context.Context, width, height uint16)
if process.handle == 0 {
return makeProcessError(process, operation, ErrAlreadyClosed, nil)
}
modifyRequest := processModifyRequest{
Operation: modifyConsoleSize,
ConsoleSize: &consoleSize{
modifyRequest := hcsschema.ProcessModifyRequest{
Operation: guestrequest.ModifyProcessConsoleSize,
ConsoleSize: &hcsschema.ConsoleSize{
Height: height,
Width: width,
},
@ -423,10 +395,10 @@ func (process *Process) CloseStdin(ctx context.Context) (err error) {
//HcsModifyProcess request to close stdin will fail if the process has already exited
if !process.stopped() {
modifyRequest := processModifyRequest{
Operation: modifyCloseHandle,
CloseHandle: &closeHandle{
Handle: stdIn,
modifyRequest := hcsschema.ProcessModifyRequest{
Operation: guestrequest.CloseProcessHandle,
CloseHandle: &hcsschema.CloseHandle{
Handle: guestrequest.STDInHandle,
},
}

View File

@ -0,0 +1,25 @@
/*
* HCS API
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* API version: 2.5
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package hcsschema
const (
CimMountFlagNone uint32 = 0x0
CimMountFlagChildOnly uint32 = 0x1
CimMountFlagEnableDax uint32 = 0x2
CimMountFlagCacheFiles uint32 = 0x4
CimMountFlagCacheRegions uint32 = 0x8
)
type CimMount struct {
ImagePath string `json:"ImagePath,omitempty"`
FileSystemName string `json:"FileSystemName,omitempty"`
VolumeGuid string `json:"VolumeGuid,omitempty"`
MountFlags uint32 `json:"MountFlags,omitempty"`
}

View File

@ -9,6 +9,8 @@
package hcsschema
import "github.com/Microsoft/hcsshim/internal/protocol/guestrequest"
type CloseHandle struct {
Handle string `json:"Handle,omitempty"`
Handle guestrequest.STDIOHandle `json:"Handle,omitempty"` // NOTE: Swagger generated as string. Locally updated.
}

View File

@ -9,8 +9,11 @@
package hcsschema
type ConsoleSize struct {
Height int32 `json:"Height,omitempty"`
// NOTE: Swagger generated fields as int32. Locally updated to uint16 to match documentation.
// https://learn.microsoft.com/en-us/virtualization/api/hcs/schemareference#ConsoleSize
Width int32 `json:"Width,omitempty"`
type ConsoleSize struct {
Height uint16 `json:"Height,omitempty"`
Width uint16 `json:"Width,omitempty"`
}

View File

@ -17,5 +17,5 @@ type IsolationSettings struct {
DebugPort int64 `json:"DebugPort,omitempty"`
// Optional data passed by host on isolated virtual machine start
LaunchData string `json:"LaunchData,omitempty"`
HclEnabled bool `json:"HclEnabled,omitempty"`
HclEnabled *bool `json:"HclEnabled,omitempty"`
}

View File

@ -9,6 +9,13 @@
package hcsschema
type FileSystemFilterType string
const (
UnionFS FileSystemFilterType = "UnionFS"
WCIFS FileSystemFilterType = "WCIFS"
)
type Layer struct {
Id string `json:"Id,omitempty"`

View File

@ -9,9 +9,11 @@
package hcsschema
// Passed to HcsRpc_ModifyProcess
import "github.com/Microsoft/hcsshim/internal/protocol/guestrequest"
// Passed to HcsRpc_ModifyProcess
type ProcessModifyRequest struct {
Operation string `json:"Operation,omitempty"`
Operation guestrequest.ProcessModifyOperation `json:"Operation,omitempty"` // NOTE: Swagger generated as string. Locally updated.
ConsoleSize *ConsoleSize `json:"ConsoleSize,omitempty"`

View File

@ -9,13 +9,16 @@
package hcsschema
// Status of a process running in a container
// NOTE: Swagger generated fields as int32. Locally updated to uint16 to match documentation.
// https://learn.microsoft.com/en-us/virtualization/api/hcs/schemareference#ConsoleSize
// Status of a process running in a container
type ProcessStatus struct {
ProcessId int32 `json:"ProcessId,omitempty"`
ProcessId uint32 `json:"ProcessId,omitempty"` // NOTE: Swagger generated as int32. Locally updated to match documentation.
Exited bool `json:"Exited,omitempty"`
ExitCode int32 `json:"ExitCode,omitempty"`
ExitCode uint32 `json:"ExitCode,omitempty"` // NOTE: Swagger generated as int32. Locally updated to match documentation.
LastWaitResult int32 `json:"LastWaitResult,omitempty"`
}

View File

@ -10,7 +10,7 @@
package hcsschema
import (
v1 "github.com/containerd/cgroups/stats/v1"
v1 "github.com/containerd/cgroups/v3/cgroup1/stats"
)
type Properties struct {

View File

@ -0,0 +1,13 @@
package hcsschema
// NOTE: manually added
type RegistryHive string
// List of RegistryHive
const (
RegistryHive_SYSTEM RegistryHive = "System"
RegistryHive_SOFTWARE RegistryHive = "Software"
RegistryHive_SECURITY RegistryHive = "Security"
RegistryHive_SAM RegistryHive = "Sam"
)

View File

@ -10,7 +10,7 @@
package hcsschema
type RegistryKey struct {
Hive string `json:"Hive,omitempty"`
Hive RegistryHive `json:"Hive,omitempty"`
Name string `json:"Name,omitempty"`

View File

@ -14,7 +14,7 @@ type RegistryValue struct {
Name string `json:"Name,omitempty"`
Type_ string `json:"Type,omitempty"`
Type_ RegistryValueType `json:"Type,omitempty"`
// One and only one value type must be set.
StringValue string `json:"StringValue,omitempty"`

View File

@ -0,0 +1,17 @@
package hcsschema
// NOTE: manually added
type RegistryValueType string
// List of RegistryValueType
const (
RegistryValueType_NONE RegistryValueType = "None"
RegistryValueType_STRING RegistryValueType = "String"
RegistryValueType_EXPANDED_STRING RegistryValueType = "ExpandedString"
RegistryValueType_MULTI_STRING RegistryValueType = "MultiString"
RegistryValueType_BINARY RegistryValueType = "Binary"
RegistryValueType_D_WORD RegistryValueType = "DWord"
RegistryValueType_Q_WORD RegistryValueType = "QWord"
RegistryValueType_CUSTOM_TYPE RegistryValueType = "CustomType"
)

View File

@ -97,7 +97,7 @@ func CreateComputeSystem(ctx context.Context, id string, hcsDocumentInterface in
events, err := processAsyncHcsResult(ctx, createError, resultJSON, computeSystem.callbackNumber,
hcsNotificationSystemCreateCompleted, &timeout.SystemCreate)
if err != nil {
if err == ErrTimeout {
if errors.Is(err, ErrTimeout) {
// Terminate the compute system if it still exists. We're okay to
// ignore a failure here.
_ = computeSystem.Terminate(ctx)
@ -238,7 +238,7 @@ func (computeSystem *System) Shutdown(ctx context.Context) error {
resultJSON, err := vmcompute.HcsShutdownComputeSystem(ctx, computeSystem.handle, "")
events := processHcsResult(ctx, resultJSON)
switch err {
switch err { //nolint:errorlint
case nil, ErrVmcomputeAlreadyStopped, ErrComputeSystemDoesNotExist, ErrVmcomputeOperationPending:
default:
return makeSystemError(computeSystem, operation, err, events)
@ -259,7 +259,7 @@ func (computeSystem *System) Terminate(ctx context.Context) error {
resultJSON, err := vmcompute.HcsTerminateComputeSystem(ctx, computeSystem.handle, "")
events := processHcsResult(ctx, resultJSON)
switch err {
switch err { //nolint:errorlint
case nil, ErrVmcomputeAlreadyStopped, ErrComputeSystemDoesNotExist, ErrVmcomputeOperationPending:
default:
return makeSystemError(computeSystem, operation, err, events)
@ -279,7 +279,7 @@ func (computeSystem *System) waitBackground() {
span.AddAttributes(trace.StringAttribute("cid", computeSystem.id))
err := waitForNotification(ctx, computeSystem.callbackNumber, hcsNotificationSystemExited, nil)
switch err {
switch err { //nolint:errorlint
case nil:
log.G(ctx).Debug("system exited")
case ErrVmcomputeUnexpectedExit:
@ -304,11 +304,22 @@ func (computeSystem *System) WaitError() error {
return computeSystem.waitError
}
// Wait synchronously waits for the compute system to shutdown or terminate. If
// the compute system has already exited returns the previous error (if any).
// Wait synchronously waits for the compute system to shutdown or terminate.
// If the compute system has already exited returns the previous error (if any).
func (computeSystem *System) Wait() error {
<-computeSystem.WaitChannel()
return computeSystem.WaitError()
return computeSystem.WaitCtx(context.Background())
}
// WaitCtx synchronously waits for the compute system to shutdown or terminate, or the context to be cancelled.
//
// See [System.Wait] for more information.
func (computeSystem *System) WaitCtx(ctx context.Context) error {
select {
case <-computeSystem.WaitChannel():
return computeSystem.WaitError()
case <-ctx.Done():
return ctx.Err()
}
}
// stopped returns true if the compute system stopped.
@ -735,9 +746,17 @@ func (computeSystem *System) OpenProcess(ctx context.Context, pid int) (*Process
}
// Close cleans up any state associated with the compute system but does not terminate or wait for it.
func (computeSystem *System) Close() (err error) {
func (computeSystem *System) Close() error {
return computeSystem.CloseCtx(context.Background())
}
// CloseCtx is similar to [System.Close], but accepts a context.
//
// The context is used for all operations, including waits, so timeouts/cancellations may prevent
// proper system cleanup.
func (computeSystem *System) CloseCtx(ctx context.Context) (err error) {
operation := "hcs::System::Close"
ctx, span := oc.StartSpan(context.Background(), operation)
ctx, span := oc.StartSpan(ctx, operation)
defer span.End()
defer func() { oc.SetSpanStatus(span, err) }()
span.AddAttributes(trace.StringAttribute("cid", computeSystem.id))

View File

@ -31,7 +31,7 @@ func hnsCallRawResponse(method, path, request string) (*hnsResponse, error) {
func hnsCall(method, path, request string, returnResponse interface{}) error {
hnsresponse, err := hnsCallRawResponse(method, path, request)
if err != nil {
return fmt.Errorf("failed during hnsCallRawResponse: %v", err)
return fmt.Errorf("failed during hnsCallRawResponse: %w", err)
}
if !hnsresponse.Success {
return fmt.Errorf("hns failed with error : %s", hnsresponse.Error)

View File

@ -56,7 +56,7 @@ func issueNamespaceRequest(id *string, method, subpath string, request interface
if strings.Contains(err.Error(), "Element not found.") {
return nil, os.ErrNotExist
}
return nil, fmt.Errorf("%s %s: %s", method, hnspath, err)
return nil, fmt.Errorf("%s %s: %w", method, hnspath, err)
}
return &ns, err
}
@ -86,7 +86,7 @@ func GetNamespaceEndpoints(id string) ([]string, error) {
var endpoint namespaceEndpointRequest
err = json.Unmarshal(rsrc.Data, &endpoint)
if err != nil {
return nil, fmt.Errorf("unmarshal endpoint: %s", err)
return nil, fmt.Errorf("unmarshal endpoint: %w", err)
}
endpoints = append(endpoints, endpoint.ID)
}

View File

@ -4,6 +4,7 @@ package jobobject
import (
"context"
"errors"
"fmt"
"sync"
"unsafe"
@ -59,7 +60,7 @@ func pollIOCP(ctx context.Context, iocpHandle windows.Handle) {
}).Warn("failed to parse job object message")
continue
}
if err := msq.Enqueue(notification); err == queue.ErrQueueClosed {
if err := msq.Enqueue(notification); errors.Is(err, queue.ErrQueueClosed) {
// Write will only return an error when the queue is closed.
// The only time a queue would ever be closed is when we call `Close` on
// the job it belongs to which also removes it from the jobMap, so something

View File

@ -167,7 +167,7 @@ func Create(ctx context.Context, options *Options) (_ *JobObject, err error) {
//
// Returns a JobObject structure and an error if there is one.
func Open(ctx context.Context, options *Options) (_ *JobObject, err error) {
if options == nil || (options != nil && options.Name == "") {
if options == nil || options.Name == "" {
return nil, errors.New("no job object name specified to open")
}
@ -374,7 +374,7 @@ func (job *JobObject) Pids() ([]uint32, error) {
return []uint32{}, nil
}
if err != winapi.ERROR_MORE_DATA {
if err != winapi.ERROR_MORE_DATA { //nolint:errorlint
return nil, fmt.Errorf("failed initial query for PIDs in job object: %w", err)
}

View File

@ -143,6 +143,13 @@ func (job *JobObject) SetCPUAffinity(affinityBitMask uint64) error {
return err
}
info.BasicLimitInformation.LimitFlags |= uint32(windows.JOB_OBJECT_LIMIT_AFFINITY)
// We really, really shouldn't be running on 32 bit, but just in case (and to satisfy CodeQL) ...
const maxUintptr = ^uintptr(0)
if affinityBitMask > uint64(maxUintptr) {
return fmt.Errorf("affinity bitmask (%d) exceeds max allowable value (%d)", affinityBitMask, maxUintptr)
}
info.BasicLimitInformation.Affinity = uintptr(affinityBitMask)
return job.setExtendedInformation(info)
}

View File

@ -8,6 +8,10 @@ import (
"net"
"reflect"
"time"
"github.com/sirupsen/logrus"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
// TimeFormat is [time.RFC3339Nano] with nanoseconds padded using
@ -61,25 +65,49 @@ func formatAddr(a net.Addr) string {
func Format(ctx context.Context, v interface{}) string {
b, err := encode(v)
if err != nil {
G(ctx).WithError(err).Warning("could not format value")
// logging errors aren't really warning worthy, and can potentially spam a lot of logs out
G(ctx).WithFields(logrus.Fields{
logrus.ErrorKey: err,
"type": fmt.Sprintf("%T", v),
}).Debug("could not format value")
return ""
}
return string(b)
}
func encode(v interface{}) ([]byte, error) {
return encodeBuffer(&bytes.Buffer{}, v)
}
func encode(v interface{}) (_ []byte, err error) {
if m, ok := v.(proto.Message); ok {
// use canonical JSON encoding for protobufs (instead of [encoding/json])
// https://protobuf.dev/programming-guides/proto3/#json
var b []byte
b, err = protojson.MarshalOptions{
AllowPartial: true,
// protobuf defaults to camel case for JSON encoding; use proto field name instead (snake case)
UseProtoNames: true,
}.Marshal(m)
if err == nil {
// the protojson marshaller tries to unmarshal anypb.Any fields, which can
// fail for types encoded with "github.com/containerd/typeurl/v2"
// we can try creating a dedicated protoregistry.MessageTypeResolver that uses typeurl, but, its
// more robust to fall back on json marshalling for errors in general
return b, nil
}
func encodeBuffer(buf *bytes.Buffer, v interface{}) ([]byte, error) {
}
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", "")
if err := enc.Encode(v); err != nil {
err = fmt.Errorf("could not marshall %T to JSON for logging: %w", v, err)
return nil, err
if jErr := enc.Encode(v); jErr != nil {
if err != nil {
// TODO (go1.20): use multierror via fmt.Errorf("...: %w; ...: %w", ...)
//nolint:errorlint // non-wrapping format verb for fmt.Errorf
return nil, fmt.Errorf("protojson encoding: %v; json encoding: %w", err, jErr)
}
return nil, fmt.Errorf("json encoding: %w", jErr)
}
// encoder.Encode appends a newline to the end

View File

@ -0,0 +1,12 @@
package log
import (
"github.com/sirupsen/logrus"
)
type NopFormatter struct{}
var _ logrus.Formatter = NopFormatter{}
// Format does nothing and returns a nil slice.
func (NopFormatter) Format(*logrus.Entry) ([]byte, error) { return nil, nil }

View File

@ -55,7 +55,7 @@ func ScrubProcessParameters(s string) (string, error) {
}
pp.Environment = map[string]string{_scrubbedReplacement: _scrubbedReplacement}
b, err := encodeBuffer(bytes.NewBuffer(b[:0]), pp)
b, err := encode(pp)
if err != nil {
return "", err
}
@ -89,11 +89,11 @@ func scrubBridgeCreate(m genMap) error {
}
func scrubLinuxHostedSystem(m genMap) error {
if m, ok := index(m, "OciSpecification"); ok {
if m, ok := index(m, "OciSpecification"); ok { //nolint:govet // shadow
if _, ok := m["annotations"]; ok {
m["annotations"] = map[string]string{_scrubbedReplacement: _scrubbedReplacement}
}
if m, ok := index(m, "process"); ok {
if m, ok := index(m, "process"); ok { //nolint:govet // shadow
if _, ok := m["env"]; ok {
m["env"] = []string{_scrubbedReplacement}
return nil
@ -113,7 +113,7 @@ func scrubExecuteProcess(m genMap) error {
if !isRequestBase(m) {
return ErrUnknownType
}
if m, ok := index(m, "Settings"); ok {
if m, ok := index(m, "Settings"); ok { //nolint:govet // shadow
if ss, ok := m["ProcessParameters"]; ok {
// ProcessParameters is a json encoded struct passed as a regular sting field
s, ok := ss.(string)

View File

@ -46,6 +46,7 @@ const (
ExpectedType = "expected-type"
Bool = "bool"
Int32 = "int32"
Uint32 = "uint32"
Uint64 = "uint64"

View File

@ -126,7 +126,7 @@ func (pa *PoolAllocator) Allocate(size uint64) (MappedRegion, error) {
// this means that there are no more regions for the current class, try expanding
if nextCls != memCls {
if err := pa.split(memCls); err != nil {
if err == ErrInvalidMemoryClass {
if errors.Is(err, ErrInvalidMemoryClass) {
return nil, ErrNotEnoughSpace
}
return nil, err
@ -147,7 +147,7 @@ func (pa *PoolAllocator) Allocate(size uint64) (MappedRegion, error) {
}
// Release marks a memory region of class `memCls` and offset `offset` as free and tries to merge smaller regions into
// a bigger one
// a bigger one.
func (pa *PoolAllocator) Release(reg MappedRegion) error {
mp := pa.pools[reg.Type()]
if mp == nil {
@ -164,7 +164,7 @@ func (pa *PoolAllocator) Release(reg MappedRegion) error {
return ErrNotAllocated
}
if err := pa.merge(n.parent); err != nil {
if err != ErrEarlyMerge {
if !errors.Is(err, ErrEarlyMerge) {
return err
}
}

View File

@ -6,7 +6,7 @@ import (
"net"
"os"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/errdefs"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
@ -16,7 +16,7 @@ import (
func toStatusCode(err error) codes.Code {
// checks if err implements GRPCStatus() *"google.golang.org/grpc/status".Status,
// wraps an error defined in "github.com/containerd/containerd/errdefs", or is a
// wraps an error defined in "github.com/containerd/errdefs", or is a
// context timeout or cancelled error
if s, ok := status.FromError(errdefs.ToGRPC(err)); ok {
return s.Code()

View File

@ -5,7 +5,7 @@ package guestrequest
type RequestType string
type ResourceType string
// RequestType const
// RequestType const.
const (
RequestTypeAdd RequestType = "Add"
RequestTypeRemove RequestType = "Remove"
@ -54,3 +54,23 @@ var (
"305891a9-b251-5dfe-91a2-c25d9212275b",
}
)
// constants for v2 schema ProcessModifyRequest
// Operation type for [hcsschema.ProcessModifyRequest].
type ProcessModifyOperation string
const (
ModifyProcessConsoleSize ProcessModifyOperation = "ConsoleSize"
CloseProcessHandle ProcessModifyOperation = "CloseHandle"
)
// Standard IO handle(s) to close for [hcsschema.CloseHandle] in [hcsschema.ProcessModifyRequest].
type STDIOHandle string
const (
STDInHandle STDIOHandle = "StdIn"
STDOutHandle STDIOHandle = "StdOut"
STDErrHandle STDIOHandle = "StdErr"
AllHandles STDIOHandle = "All"
)

View File

@ -4,6 +4,7 @@ package regstate
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
@ -44,8 +45,8 @@ func (err *NotFoundError) Error() string {
}
func IsNotFoundError(err error) bool {
_, ok := err.(*NotFoundError)
return ok
var e *NotFoundError
return errors.As(err, &e)
}
type NoStateError struct {
@ -152,7 +153,8 @@ func (k *Key) openid(id string) (*Key, error) {
escaped := url.PathEscape(id)
fullpath := filepath.Join(k.Name, escaped)
nk, err := k.open(escaped)
if perr, ok := err.(*os.PathError); ok && perr.Err == syscall.ERROR_FILE_NOT_FOUND {
var perr *os.PathError
if errors.As(err, &perr) && errors.Is(perr.Err, syscall.ERROR_FILE_NOT_FOUND) {
return nil, &NotFoundError{id}
}
if err != nil {
@ -165,7 +167,7 @@ func (k *Key) Remove(id string) error {
escaped := url.PathEscape(id)
err := registry.DeleteKey(k.Key, escaped)
if err != nil {
if err == syscall.ERROR_FILE_NOT_FOUND {
if err == syscall.ERROR_FILE_NOT_FOUND { //nolint:errorlint
return &NotFoundError{id}
}
return &os.PathError{Op: "RegDeleteKey", Path: filepath.Join(k.Name, escaped), Err: err}
@ -215,7 +217,7 @@ func (k *Key) set(id string, create bool, key string, state interface{}) error {
err = sk.SetBinaryValue(key, js)
}
if err != nil {
if err == syscall.ERROR_FILE_NOT_FOUND {
if err == syscall.ERROR_FILE_NOT_FOUND { //nolint:errorlint
return &NoStateError{id, key}
}
return &os.PathError{Op: "RegSetValueEx", Path: sk.Name + ":" + key, Err: err}
@ -239,7 +241,7 @@ func (k *Key) Clear(id, key string) error {
defer sk.Close()
err = sk.DeleteValue(key)
if err != nil {
if err == syscall.ERROR_FILE_NOT_FOUND {
if err == syscall.ERROR_FILE_NOT_FOUND { //nolint:errorlint
return &NoStateError{id, key}
}
return &os.PathError{Op: "RegDeleteValue", Path: sk.Name + ":" + key, Err: err}
@ -278,7 +280,7 @@ func (k *Key) Get(id, key string, state interface{}) error {
js, _, err = sk.GetBinaryValue(key)
}
if err != nil {
if err == syscall.ERROR_FILE_NOT_FOUND {
if err == syscall.ERROR_FILE_NOT_FOUND { //nolint:errorlint
return &NoStateError{id, key}
}
return &os.PathError{Op: "RegQueryValueEx", Path: sk.Name + ":" + key, Err: err}

View File

@ -243,7 +243,7 @@ func RemoveRelative(path string, root *os.File) error {
if err == nil {
defer f.Close()
err = deleteOnClose(f)
if err == syscall.ERROR_ACCESS_DENIED {
if err == syscall.ERROR_ACCESS_DENIED { //nolint:errorlint
// Maybe the file is marked readonly. Clear the bit and retry.
_ = clearReadOnly(f)
err = deleteOnClose(f)
@ -276,7 +276,7 @@ func RemoveAllRelative(path string, root *os.File) error {
}
// It is necessary to use os.Open as Readdirnames does not work with
// OpenRelative. This is safe because the above lstatrelative fails
// OpenRelative. This is safe because the above LstatRelative fails
// if the target is outside the root, and we know this is not a
// symlink from the above FILE_ATTRIBUTE_REPARSE_POINT check.
fd, err := os.Open(filepath.Join(root.Name(), path))
@ -293,12 +293,12 @@ func RemoveAllRelative(path string, root *os.File) error {
for {
names, err1 := fd.Readdirnames(100)
for _, name := range names {
err1 := RemoveAllRelative(path+string(os.PathSeparator)+name, root)
if err == nil {
err = err1
if err2 := RemoveAllRelative(path+string(os.PathSeparator)+name, root); err == nil {
err = err2
}
}
if err1 == io.EOF {
// Readdirnames has no more files to return
break
}
// If Readdirnames returned an error, use it.

View File

@ -104,7 +104,7 @@ func execute(ctx gcontext.Context, timeout time.Duration, f func() error) error
}()
select {
case <-ctx.Done():
if ctx.Err() == gcontext.DeadlineExceeded {
if ctx.Err() == gcontext.DeadlineExceeded { //nolint:errorlint
log.G(ctx).WithField(logfields.Timeout, trueTimeout).
Warning("Syscall did not complete within operation timeout. This may indicate a platform issue. " +
"If it appears to be making no forward progress, obtain the stacks and see if there is a syscall " +
@ -150,7 +150,7 @@ func HcsCreateComputeSystem(ctx gcontext.Context, id string, configuration strin
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@ -205,7 +205,7 @@ func HcsStartComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, option
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@ -228,7 +228,7 @@ func HcsShutdownComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, opt
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@ -251,7 +251,7 @@ func HcsTerminateComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, op
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@ -274,7 +274,7 @@ func HcsPauseComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, option
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@ -297,7 +297,7 @@ func HcsResumeComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, optio
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()
@ -621,7 +621,7 @@ func HcsSaveComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options
if result != "" {
span.AddAttributes(trace.StringAttribute("result", result))
}
if hr != errVmcomputeOperationPending {
if hr != errVmcomputeOperationPending { //nolint:errorlint // explicitly returned
oc.SetSpanStatus(span, hr)
}
}()

View File

@ -1,3 +1,5 @@
//go:build windows
package wclayer
import (
@ -64,7 +66,7 @@ func (r *baseLayerReader) walkUntilCancelled() error {
return nil
})
if err == errorIterationCanceled {
if err == errorIterationCanceled { //nolint:errorlint // explicitly returned
return nil
}
@ -72,8 +74,8 @@ func (r *baseLayerReader) walkUntilCancelled() error {
return err
}
utilityVMAbsPath := filepath.Join(r.root, utilityVMPath)
utilityVMFilesAbsPath := filepath.Join(r.root, utilityVMFilesPath)
utilityVMAbsPath := filepath.Join(r.root, UtilityVMPath)
utilityVMFilesAbsPath := filepath.Join(r.root, UtilityVMFilesPath)
// Ignore a UtilityVM without Files, that's not _really_ a UtiltyVM
if _, err = os.Lstat(utilityVMFilesAbsPath); err != nil {
@ -103,7 +105,7 @@ func (r *baseLayerReader) walkUntilCancelled() error {
return nil
})
if err == errorIterationCanceled {
if err == errorIterationCanceled { //nolint:errorlint // explicitly returned
return nil
}

View File

@ -1,3 +1,5 @@
//go:build windows
package wclayer
import (
@ -5,7 +7,6 @@ import (
"fmt"
"os"
"path/filepath"
"syscall"
"github.com/Microsoft/hcsshim/internal/hcserror"
"github.com/Microsoft/hcsshim/internal/longpath"
@ -37,7 +38,7 @@ func ensureHive(path string, root *os.File) (err error) {
return fmt.Errorf("getting path: %w", err)
}
var key syscall.Handle
var key winapi.ORHKey
err = winapi.ORCreateHive(&key)
if err != nil {
return fmt.Errorf("creating hive: %w", err)
@ -72,7 +73,7 @@ func ensureBaseLayer(root *os.File) (hasUtilityVM bool, err error) {
}
}
stat, err := safefile.LstatRelative(utilityVMFilesPath, root)
stat, err := safefile.LstatRelative(UtilityVMFilesPath, root)
if os.IsNotExist(err) {
return false, nil
@ -83,7 +84,7 @@ func ensureBaseLayer(root *os.File) (hasUtilityVM bool, err error) {
}
if !stat.Mode().IsDir() {
fullPath := filepath.Join(root.Name(), utilityVMFilesPath)
fullPath := filepath.Join(root.Name(), UtilityVMFilesPath)
return false, errors.Errorf("%s has unexpected file mode %s", fullPath, stat.Mode().String())
}
@ -92,7 +93,7 @@ func ensureBaseLayer(root *os.File) (hasUtilityVM bool, err error) {
// Just check that this exists as a regular file. If it exists but is not a valid registry hive,
// ProcessUtilityVMImage will complain:
// "The registry could not read in, or write out, or flush, one of the files that contain the system's image of the registry."
bcdPath := filepath.Join(utilityVMFilesPath, bcdRelativePath)
bcdPath := filepath.Join(UtilityVMFilesPath, bcdRelativePath)
stat, err = safefile.LstatRelative(bcdPath, root)
if err != nil {
@ -122,12 +123,12 @@ func convertToBaseLayer(ctx context.Context, root *os.File) error {
return nil
}
err = safefile.EnsureNotReparsePointRelative(utilityVMPath, root)
err = safefile.EnsureNotReparsePointRelative(UtilityVMPath, root)
if err != nil {
return err
}
utilityVMPath := filepath.Join(root.Name(), utilityVMPath)
utilityVMPath := filepath.Join(root.Name(), UtilityVMPath)
return ProcessUtilityVMImage(ctx, utilityVMPath)
}

View File

@ -11,7 +11,6 @@ import (
"github.com/Microsoft/hcsshim/internal/hcserror"
"github.com/Microsoft/hcsshim/internal/oc"
"github.com/Microsoft/hcsshim/osversion"
"go.opencensus.io/trace"
)
@ -30,14 +29,17 @@ func ExpandScratchSize(ctx context.Context, path string, size uint64) (err error
return hcserror.New(err, title, "")
}
// Manually expand the volume now in order to work around bugs in 19H1 and
// prerelease versions of Vb. Remove once this is fixed in Windows.
if build := osversion.Build(); build >= osversion.V19H1 && build < 19020 {
err = expandSandboxVolume(ctx, path)
if err != nil {
return err
}
// Always expand the volume too. In case of legacy layers not expanding the volume here works because
// the PrepareLayer call internally handles the expansion. However, in other cases (like CimFS) we
// don't call PrepareLayer and so the volume will never be expanded. This also means in case of
// legacy layers, we might have a small perf hit because the VHD is mounted twice for expansion (once
// here and once during the PrepareLayer call). But as long as the perf hit is minimal, we should be
// okay.
err = expandSandboxVolume(ctx, path)
if err != nil {
return err
}
return nil
}

View File

@ -7,6 +7,10 @@ package wclayer
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"syscall"
"github.com/Microsoft/go-winio/pkg/guid"
@ -101,3 +105,23 @@ func layerPathsToDescriptors(ctx context.Context, parentLayerPaths []string) ([]
return layers, nil
}
// GetLayerUvmBuild looks for a file named `uvmbuildversion` at `layerPath\uvmbuildversion` and returns the
// build number of the UVM from that file.
func GetLayerUvmBuild(layerPath string) (uint16, error) {
data, err := os.ReadFile(filepath.Join(layerPath, UvmBuildFileName))
if err != nil {
return 0, err
}
ver, err := strconv.ParseUint(string(data), 10, 16)
if err != nil {
return 0, err
}
return uint16(ver), nil
}
// WriteLayerUvmBuildFile writes a file at path `layerPath\uvmbuildversion` that contains the given `build`
// version for future reference.
func WriteLayerUvmBuildFile(layerPath string, build uint16) error {
return os.WriteFile(filepath.Join(layerPath, UvmBuildFileName), []byte(fmt.Sprintf("%d", build)), 0777)
}

View File

@ -29,10 +29,19 @@ var mutatedUtilityVMFiles = map[string]bool{
}
const (
filesPath = `Files`
hivesPath = `Hives`
utilityVMPath = `UtilityVM`
utilityVMFilesPath = `UtilityVM\Files`
filesPath = `Files`
HivesPath = `Hives`
UtilityVMPath = `UtilityVM`
UtilityVMFilesPath = `UtilityVM\Files`
RegFilesPath = `Files\Windows\System32\config`
BcdFilePath = `UtilityVM\Files\EFI\Microsoft\Boot\BCD`
BootMgrFilePath = `UtilityVM\Files\EFI\Microsoft\Boot\bootmgfw.efi`
ContainerBaseVhd = `blank-base.vhdx`
ContainerScratchVhd = `blank.vhdx`
UtilityVMBaseVhd = `SystemTemplateBase.vhdx`
UtilityVMScratchVhd = `SystemTemplate.vhdx`
LayoutFileName = `layout`
UvmBuildFileName = `uvmbuildversion`
)
func openFileOrDir(path string, mode uint32, createDisposition uint32) (file *os.File, err error) {
@ -145,7 +154,7 @@ func (r *legacyLayerReader) walkUntilCancelled() error {
}
return nil
})
if err == errorIterationCanceled {
if err == errorIterationCanceled { //nolint:errorlint // explicitly returned
return nil
}
if err == nil {
@ -187,7 +196,7 @@ func findBackupStreamSize(r io.Reader) (int64, error) {
for {
hdr, err := br.Next()
if err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
err = nil
}
return 0, err
@ -243,11 +252,11 @@ func (r *legacyLayerReader) Next() (path string, size int64, fileInfo *winio.Fil
if !hasPathPrefix(path, filesPath) {
size = fe.fi.Size()
r.backupReader = winio.NewBackupFileReader(f, false)
if path == hivesPath || path == filesPath {
if path == HivesPath || path == filesPath {
// The Hives directory has a non-deterministic file time because of the
// nature of the import process. Use the times from System_Delta.
var g *os.File
g, err = os.Open(filepath.Join(r.root, hivesPath, `System_Delta`))
g, err = os.Open(filepath.Join(r.root, HivesPath, `System_Delta`))
if err != nil {
return
}
@ -409,7 +418,7 @@ func (w *legacyLayerWriter) CloseRoots() {
func (w *legacyLayerWriter) initUtilityVM() error {
if !w.HasUtilityVM {
err := safefile.MkdirRelative(utilityVMPath, w.destRoot)
err := safefile.MkdirRelative(UtilityVMPath, w.destRoot)
if err != nil {
return err
}
@ -417,9 +426,9 @@ func (w *legacyLayerWriter) initUtilityVM() error {
// clone the utility VM from the parent layer into this layer. Use hard
// links to avoid unnecessary copying, since most of the files are
// immutable.
err = cloneTree(w.parentRoots[0], w.destRoot, utilityVMFilesPath, mutatedUtilityVMFiles)
err = cloneTree(w.parentRoots[0], w.destRoot, UtilityVMFilesPath, mutatedUtilityVMFiles)
if err != nil {
return fmt.Errorf("cloning the parent utility VM image failed: %s", err)
return fmt.Errorf("cloning the parent utility VM image failed: %w", err)
}
w.HasUtilityVM = true
}
@ -442,7 +451,7 @@ func (w *legacyLayerWriter) reset() error {
for {
bhdr, err := br.Next()
if err == io.EOF {
if errors.Is(err, io.EOF) {
// end of backupstream data
break
}
@ -592,7 +601,7 @@ func (w *legacyLayerWriter) Add(name string, fileInfo *winio.FileBasicInfo) erro
return err
}
if name == utilityVMPath {
if name == UtilityVMPath {
return w.initUtilityVM()
}
@ -601,11 +610,11 @@ func (w *legacyLayerWriter) Add(name string, fileInfo *winio.FileBasicInfo) erro
}
name = filepath.Clean(name)
if hasPathPrefix(name, utilityVMPath) {
if hasPathPrefix(name, UtilityVMPath) {
if !w.HasUtilityVM {
return errors.New("missing UtilityVM directory")
}
if !hasPathPrefix(name, utilityVMFilesPath) && name != utilityVMFilesPath {
if !hasPathPrefix(name, UtilityVMFilesPath) && name != UtilityVMFilesPath {
return errors.New("invalid UtilityVM layer")
}
createDisposition := uint32(winapi.FILE_OPEN)
@ -699,7 +708,7 @@ func (w *legacyLayerWriter) Add(name string, fileInfo *winio.FileBasicInfo) erro
return err
}
if hasPathPrefix(name, hivesPath) {
if hasPathPrefix(name, HivesPath) {
w.backupWriter = winio.NewBackupFileWriter(f, false)
w.bufWriter.Reset(w.backupWriter)
} else {
@ -731,14 +740,14 @@ func (w *legacyLayerWriter) AddLink(name string, target string) error {
// Look for cross-layer hard link targets in the parent layers, since
// nothing is in the destination path yet.
roots = w.parentRoots
} else if hasPathPrefix(target, utilityVMFilesPath) {
} else if hasPathPrefix(target, UtilityVMFilesPath) {
// Since the utility VM is fully cloned into the destination path
// already, look for cross-layer hard link targets directly in the
// destination path.
roots = []*os.File{w.destRoot}
}
if roots == nil || (!hasPathPrefix(name, filesPath) && !hasPathPrefix(name, utilityVMFilesPath)) {
if roots == nil || (!hasPathPrefix(name, filesPath) && !hasPathPrefix(name, UtilityVMFilesPath)) {
return errors.New("invalid hard link in layer")
}
@ -777,7 +786,7 @@ func (w *legacyLayerWriter) Remove(name string) error {
name = filepath.Clean(name)
if hasPathPrefix(name, filesPath) {
w.Tombstones = append(w.Tombstones, name)
} else if hasPathPrefix(name, utilityVMFilesPath) {
} else if hasPathPrefix(name, UtilityVMFilesPath) {
err := w.initUtilityVM()
if err != nil {
return err

View File

@ -0,0 +1,47 @@
//go:build windows
package winapi
import (
"unsafe"
"github.com/Microsoft/go-winio/pkg/guid"
"golang.org/x/sys/windows"
)
type g = guid.GUID
type FsHandle uintptr
type StreamHandle uintptr
type CimFsFileMetadata struct {
Attributes uint32
FileSize int64
CreationTime windows.Filetime
LastWriteTime windows.Filetime
ChangeTime windows.Filetime
LastAccessTime windows.Filetime
SecurityDescriptorBuffer unsafe.Pointer
SecurityDescriptorSize uint32
ReparseDataBuffer unsafe.Pointer
ReparseDataSize uint32
ExtendedAttributes unsafe.Pointer
EACount uint32
}
//sys CimMountImage(imagePath string, fsName string, flags uint32, volumeID *g) (hr error) = cimfs.CimMountImage?
//sys CimDismountImage(volumeID *g) (hr error) = cimfs.CimDismountImage?
//sys CimCreateImage(imagePath string, oldFSName *uint16, newFSName *uint16, cimFSHandle *FsHandle) (hr error) = cimfs.CimCreateImage?
//sys CimCloseImage(cimFSHandle FsHandle) = cimfs.CimCloseImage?
//sys CimCommitImage(cimFSHandle FsHandle) (hr error) = cimfs.CimCommitImage?
//sys CimCreateFile(cimFSHandle FsHandle, path string, file *CimFsFileMetadata, cimStreamHandle *StreamHandle) (hr error) = cimfs.CimCreateFile?
//sys CimCloseStream(cimStreamHandle StreamHandle) (hr error) = cimfs.CimCloseStream?
//sys CimWriteStream(cimStreamHandle StreamHandle, buffer uintptr, bufferSize uint32) (hr error) = cimfs.CimWriteStream?
//sys CimDeletePath(cimFSHandle FsHandle, path string) (hr error) = cimfs.CimDeletePath?
//sys CimCreateHardLink(cimFSHandle FsHandle, newPath string, oldPath string) (hr error) = cimfs.CimCreateHardLink?
//sys CimCreateAlternateStream(cimFSHandle FsHandle, path string, size uint64, cimStreamHandle *StreamHandle) (hr error) = cimfs.CimCreateAlternateStream?

View File

@ -0,0 +1,37 @@
package winapi
// Offline registry management API
type ORHKey uintptr
type RegType uint32
const (
// Registry value types: https://docs.microsoft.com/en-us/windows/win32/sysinfo/registry-value-types
REG_TYPE_NONE RegType = 0
REG_TYPE_SZ RegType = 1
REG_TYPE_EXPAND_SZ RegType = 2
REG_TYPE_BINARY RegType = 3
REG_TYPE_DWORD RegType = 4
REG_TYPE_DWORD_LITTLE_ENDIAN RegType = 4
REG_TYPE_DWORD_BIG_ENDIAN RegType = 5
REG_TYPE_LINK RegType = 6
REG_TYPE_MULTI_SZ RegType = 7
REG_TYPE_RESOURCE_LIST RegType = 8
REG_TYPE_FULL_RESOURCE_DESCRIPTOR RegType = 9
REG_TYPE_RESOURCE_REQUIREMENTS_LIST RegType = 10
REG_TYPE_QWORD RegType = 11
REG_TYPE_QWORD_LITTLE_ENDIAN RegType = 11
)
//sys ORCreateHive(key *ORHKey) (win32err error) = offreg.ORCreateHive
//sys ORMergeHives(hiveHandles []ORHKey, result *ORHKey) (win32err error) = offreg.ORMergeHives
//sys OROpenHive(hivePath string, result *ORHKey) (win32err error) = offreg.OROpenHive
//sys ORCloseHive(handle ORHKey) (win32err error) = offreg.ORCloseHive
//sys ORSaveHive(handle ORHKey, hivePath string, osMajorVersion uint32, osMinorVersion uint32) (win32err error) = offreg.ORSaveHive
//sys OROpenKey(handle ORHKey, subKey string, result *ORHKey) (win32err error) = offreg.OROpenKey
//sys ORCloseKey(handle ORHKey) (win32err error) = offreg.ORCloseKey
//sys ORCreateKey(handle ORHKey, subKey string, class uintptr, options uint32, securityDescriptor uintptr, result *ORHKey, disposition *uint32) (win32err error) = offreg.ORCreateKey
//sys ORDeleteKey(handle ORHKey, subKey string) (win32err error) = offreg.ORDeleteKey
//sys ORGetValue(handle ORHKey, subKey string, value string, valueType *uint32, data *byte, dataLen *uint32) (win32err error) = offreg.ORGetValue
//sys ORSetValue(handle ORHKey, valueName string, valueType uint32, data *byte, dataLen uint32) (win32err error) = offreg.ORSetValue

View File

@ -1,5 +0,0 @@
package winapi
//sys ORCreateHive(key *syscall.Handle) (regerrno error) = offreg.ORCreateHive
//sys ORSaveHive(key syscall.Handle, file string, OsMajorVersion uint32, OsMinorVersion uint32) (regerrno error) = offreg.ORSaveHive
//sys ORCloseHive(key syscall.Handle) (regerrno error) = offreg.ORCloseHive

View File

@ -4,7 +4,6 @@ package winapi
import (
"errors"
"reflect"
"syscall"
"unsafe"
@ -14,11 +13,7 @@ import (
// Uint16BufferToSlice wraps a uint16 pointer-and-length into a slice
// for easier interop with Go APIs
func Uint16BufferToSlice(buffer *uint16, bufferLength int) (result []uint16) {
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&result))
hdr.Data = uintptr(unsafe.Pointer(buffer))
hdr.Cap = bufferLength
hdr.Len = bufferLength
result = unsafe.Slice(buffer, bufferLength)
return
}
@ -80,3 +75,9 @@ func ConvertStringSetToSlice(buf []byte) ([]string, error) {
}
return nil, errors.New("string set malformed: missing null terminator at end of buffer")
}
// ParseUtf16LE parses a UTF-16LE byte array into a string (without passing
// through a uint16 or rune array).
func ParseUtf16LE(b []byte) string {
return windows.UTF16PtrToString((*uint16)(unsafe.Pointer(&b[0])))
}

View File

@ -43,6 +43,7 @@ var (
modadvapi32 = windows.NewLazySystemDLL("advapi32.dll")
modbindfltapi = windows.NewLazySystemDLL("bindfltapi.dll")
modcfgmgr32 = windows.NewLazySystemDLL("cfgmgr32.dll")
modcimfs = windows.NewLazySystemDLL("cimfs.dll")
modiphlpapi = windows.NewLazySystemDLL("iphlpapi.dll")
modkernel32 = windows.NewLazySystemDLL("kernel32.dll")
modnetapi32 = windows.NewLazySystemDLL("netapi32.dll")
@ -55,6 +56,17 @@ var (
procCM_Get_Device_ID_ListA = modcfgmgr32.NewProc("CM_Get_Device_ID_ListA")
procCM_Get_Device_ID_List_SizeA = modcfgmgr32.NewProc("CM_Get_Device_ID_List_SizeA")
procCM_Locate_DevNodeW = modcfgmgr32.NewProc("CM_Locate_DevNodeW")
procCimCloseImage = modcimfs.NewProc("CimCloseImage")
procCimCloseStream = modcimfs.NewProc("CimCloseStream")
procCimCommitImage = modcimfs.NewProc("CimCommitImage")
procCimCreateAlternateStream = modcimfs.NewProc("CimCreateAlternateStream")
procCimCreateFile = modcimfs.NewProc("CimCreateFile")
procCimCreateHardLink = modcimfs.NewProc("CimCreateHardLink")
procCimCreateImage = modcimfs.NewProc("CimCreateImage")
procCimDeletePath = modcimfs.NewProc("CimDeletePath")
procCimDismountImage = modcimfs.NewProc("CimDismountImage")
procCimMountImage = modcimfs.NewProc("CimMountImage")
procCimWriteStream = modcimfs.NewProc("CimWriteStream")
procSetJobCompartmentId = modiphlpapi.NewProc("SetJobCompartmentId")
procClosePseudoConsole = modkernel32.NewProc("ClosePseudoConsole")
procCopyFileW = modkernel32.NewProc("CopyFileW")
@ -84,8 +96,16 @@ var (
procNtSetInformationFile = modntdll.NewProc("NtSetInformationFile")
procRtlNtStatusToDosError = modntdll.NewProc("RtlNtStatusToDosError")
procORCloseHive = modoffreg.NewProc("ORCloseHive")
procORCloseKey = modoffreg.NewProc("ORCloseKey")
procORCreateHive = modoffreg.NewProc("ORCreateHive")
procORCreateKey = modoffreg.NewProc("ORCreateKey")
procORDeleteKey = modoffreg.NewProc("ORDeleteKey")
procORGetValue = modoffreg.NewProc("ORGetValue")
procORMergeHives = modoffreg.NewProc("ORMergeHives")
procOROpenHive = modoffreg.NewProc("OROpenHive")
procOROpenKey = modoffreg.NewProc("OROpenKey")
procORSaveHive = modoffreg.NewProc("ORSaveHive")
procORSetValue = modoffreg.NewProc("ORSetValue")
)
func LogonUser(username *uint16, domain *uint16, password *uint16, logonType uint32, logonProvider uint32, token *windows.Token) (err error) {
@ -164,6 +184,229 @@ func _CMLocateDevNode(pdnDevInst *uint32, pDeviceID *uint16, uFlags uint32) (hr
return
}
func CimCloseImage(cimFSHandle FsHandle) (err error) {
err = procCimCloseImage.Find()
if err != nil {
return
}
syscall.Syscall(procCimCloseImage.Addr(), 1, uintptr(cimFSHandle), 0, 0)
return
}
func CimCloseStream(cimStreamHandle StreamHandle) (hr error) {
hr = procCimCloseStream.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall(procCimCloseStream.Addr(), 1, uintptr(cimStreamHandle), 0, 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func CimCommitImage(cimFSHandle FsHandle) (hr error) {
hr = procCimCommitImage.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall(procCimCommitImage.Addr(), 1, uintptr(cimFSHandle), 0, 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func CimCreateAlternateStream(cimFSHandle FsHandle, path string, size uint64, cimStreamHandle *StreamHandle) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(path)
if hr != nil {
return
}
return _CimCreateAlternateStream(cimFSHandle, _p0, size, cimStreamHandle)
}
func _CimCreateAlternateStream(cimFSHandle FsHandle, path *uint16, size uint64, cimStreamHandle *StreamHandle) (hr error) {
hr = procCimCreateAlternateStream.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall6(procCimCreateAlternateStream.Addr(), 4, uintptr(cimFSHandle), uintptr(unsafe.Pointer(path)), uintptr(size), uintptr(unsafe.Pointer(cimStreamHandle)), 0, 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func CimCreateFile(cimFSHandle FsHandle, path string, file *CimFsFileMetadata, cimStreamHandle *StreamHandle) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(path)
if hr != nil {
return
}
return _CimCreateFile(cimFSHandle, _p0, file, cimStreamHandle)
}
func _CimCreateFile(cimFSHandle FsHandle, path *uint16, file *CimFsFileMetadata, cimStreamHandle *StreamHandle) (hr error) {
hr = procCimCreateFile.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall6(procCimCreateFile.Addr(), 4, uintptr(cimFSHandle), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(file)), uintptr(unsafe.Pointer(cimStreamHandle)), 0, 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func CimCreateHardLink(cimFSHandle FsHandle, newPath string, oldPath string) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(newPath)
if hr != nil {
return
}
var _p1 *uint16
_p1, hr = syscall.UTF16PtrFromString(oldPath)
if hr != nil {
return
}
return _CimCreateHardLink(cimFSHandle, _p0, _p1)
}
func _CimCreateHardLink(cimFSHandle FsHandle, newPath *uint16, oldPath *uint16) (hr error) {
hr = procCimCreateHardLink.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall(procCimCreateHardLink.Addr(), 3, uintptr(cimFSHandle), uintptr(unsafe.Pointer(newPath)), uintptr(unsafe.Pointer(oldPath)))
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func CimCreateImage(imagePath string, oldFSName *uint16, newFSName *uint16, cimFSHandle *FsHandle) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(imagePath)
if hr != nil {
return
}
return _CimCreateImage(_p0, oldFSName, newFSName, cimFSHandle)
}
func _CimCreateImage(imagePath *uint16, oldFSName *uint16, newFSName *uint16, cimFSHandle *FsHandle) (hr error) {
hr = procCimCreateImage.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall6(procCimCreateImage.Addr(), 4, uintptr(unsafe.Pointer(imagePath)), uintptr(unsafe.Pointer(oldFSName)), uintptr(unsafe.Pointer(newFSName)), uintptr(unsafe.Pointer(cimFSHandle)), 0, 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func CimDeletePath(cimFSHandle FsHandle, path string) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(path)
if hr != nil {
return
}
return _CimDeletePath(cimFSHandle, _p0)
}
func _CimDeletePath(cimFSHandle FsHandle, path *uint16) (hr error) {
hr = procCimDeletePath.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall(procCimDeletePath.Addr(), 2, uintptr(cimFSHandle), uintptr(unsafe.Pointer(path)), 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func CimDismountImage(volumeID *g) (hr error) {
hr = procCimDismountImage.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall(procCimDismountImage.Addr(), 1, uintptr(unsafe.Pointer(volumeID)), 0, 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func CimMountImage(imagePath string, fsName string, flags uint32, volumeID *g) (hr error) {
var _p0 *uint16
_p0, hr = syscall.UTF16PtrFromString(imagePath)
if hr != nil {
return
}
var _p1 *uint16
_p1, hr = syscall.UTF16PtrFromString(fsName)
if hr != nil {
return
}
return _CimMountImage(_p0, _p1, flags, volumeID)
}
func _CimMountImage(imagePath *uint16, fsName *uint16, flags uint32, volumeID *g) (hr error) {
hr = procCimMountImage.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall6(procCimMountImage.Addr(), 4, uintptr(unsafe.Pointer(imagePath)), uintptr(unsafe.Pointer(fsName)), uintptr(flags), uintptr(unsafe.Pointer(volumeID)), 0, 0)
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func CimWriteStream(cimStreamHandle StreamHandle, buffer uintptr, bufferSize uint32) (hr error) {
hr = procCimWriteStream.Find()
if hr != nil {
return
}
r0, _, _ := syscall.Syscall(procCimWriteStream.Addr(), 3, uintptr(cimStreamHandle), uintptr(buffer), uintptr(bufferSize))
if int32(r0) < 0 {
if r0&0x1fff0000 == 0x00070000 {
r0 &= 0xffff
}
hr = syscall.Errno(r0)
}
return
}
func SetJobCompartmentId(handle windows.Handle, compartmentId uint32) (win32Err error) {
r0, _, _ := syscall.Syscall(procSetJobCompartmentId.Addr(), 2, uintptr(handle), uintptr(compartmentId), 0)
if r0 != 0 {
@ -381,35 +624,162 @@ func RtlNtStatusToDosError(status uint32) (winerr error) {
return
}
func ORCloseHive(key syscall.Handle) (regerrno error) {
r0, _, _ := syscall.Syscall(procORCloseHive.Addr(), 1, uintptr(key), 0, 0)
func ORCloseHive(handle ORHKey) (win32err error) {
r0, _, _ := syscall.Syscall(procORCloseHive.Addr(), 1, uintptr(handle), 0, 0)
if r0 != 0 {
regerrno = syscall.Errno(r0)
win32err = syscall.Errno(r0)
}
return
}
func ORCreateHive(key *syscall.Handle) (regerrno error) {
func ORCloseKey(handle ORHKey) (win32err error) {
r0, _, _ := syscall.Syscall(procORCloseKey.Addr(), 1, uintptr(handle), 0, 0)
if r0 != 0 {
win32err = syscall.Errno(r0)
}
return
}
func ORCreateHive(key *ORHKey) (win32err error) {
r0, _, _ := syscall.Syscall(procORCreateHive.Addr(), 1, uintptr(unsafe.Pointer(key)), 0, 0)
if r0 != 0 {
regerrno = syscall.Errno(r0)
win32err = syscall.Errno(r0)
}
return
}
func ORSaveHive(key syscall.Handle, file string, OsMajorVersion uint32, OsMinorVersion uint32) (regerrno error) {
func ORCreateKey(handle ORHKey, subKey string, class uintptr, options uint32, securityDescriptor uintptr, result *ORHKey, disposition *uint32) (win32err error) {
var _p0 *uint16
_p0, regerrno = syscall.UTF16PtrFromString(file)
if regerrno != nil {
_p0, win32err = syscall.UTF16PtrFromString(subKey)
if win32err != nil {
return
}
return _ORSaveHive(key, _p0, OsMajorVersion, OsMinorVersion)
return _ORCreateKey(handle, _p0, class, options, securityDescriptor, result, disposition)
}
func _ORSaveHive(key syscall.Handle, file *uint16, OsMajorVersion uint32, OsMinorVersion uint32) (regerrno error) {
r0, _, _ := syscall.Syscall6(procORSaveHive.Addr(), 4, uintptr(key), uintptr(unsafe.Pointer(file)), uintptr(OsMajorVersion), uintptr(OsMinorVersion), 0, 0)
func _ORCreateKey(handle ORHKey, subKey *uint16, class uintptr, options uint32, securityDescriptor uintptr, result *ORHKey, disposition *uint32) (win32err error) {
r0, _, _ := syscall.Syscall9(procORCreateKey.Addr(), 7, uintptr(handle), uintptr(unsafe.Pointer(subKey)), uintptr(class), uintptr(options), uintptr(securityDescriptor), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition)), 0, 0)
if r0 != 0 {
regerrno = syscall.Errno(r0)
win32err = syscall.Errno(r0)
}
return
}
func ORDeleteKey(handle ORHKey, subKey string) (win32err error) {
var _p0 *uint16
_p0, win32err = syscall.UTF16PtrFromString(subKey)
if win32err != nil {
return
}
return _ORDeleteKey(handle, _p0)
}
func _ORDeleteKey(handle ORHKey, subKey *uint16) (win32err error) {
r0, _, _ := syscall.Syscall(procORDeleteKey.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(subKey)), 0)
if r0 != 0 {
win32err = syscall.Errno(r0)
}
return
}
func ORGetValue(handle ORHKey, subKey string, value string, valueType *uint32, data *byte, dataLen *uint32) (win32err error) {
var _p0 *uint16
_p0, win32err = syscall.UTF16PtrFromString(subKey)
if win32err != nil {
return
}
var _p1 *uint16
_p1, win32err = syscall.UTF16PtrFromString(value)
if win32err != nil {
return
}
return _ORGetValue(handle, _p0, _p1, valueType, data, dataLen)
}
func _ORGetValue(handle ORHKey, subKey *uint16, value *uint16, valueType *uint32, data *byte, dataLen *uint32) (win32err error) {
r0, _, _ := syscall.Syscall6(procORGetValue.Addr(), 6, uintptr(handle), uintptr(unsafe.Pointer(subKey)), uintptr(unsafe.Pointer(value)), uintptr(unsafe.Pointer(valueType)), uintptr(unsafe.Pointer(data)), uintptr(unsafe.Pointer(dataLen)))
if r0 != 0 {
win32err = syscall.Errno(r0)
}
return
}
func ORMergeHives(hiveHandles []ORHKey, result *ORHKey) (win32err error) {
var _p0 *ORHKey
if len(hiveHandles) > 0 {
_p0 = &hiveHandles[0]
}
r0, _, _ := syscall.Syscall(procORMergeHives.Addr(), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(hiveHandles)), uintptr(unsafe.Pointer(result)))
if r0 != 0 {
win32err = syscall.Errno(r0)
}
return
}
func OROpenHive(hivePath string, result *ORHKey) (win32err error) {
var _p0 *uint16
_p0, win32err = syscall.UTF16PtrFromString(hivePath)
if win32err != nil {
return
}
return _OROpenHive(_p0, result)
}
func _OROpenHive(hivePath *uint16, result *ORHKey) (win32err error) {
r0, _, _ := syscall.Syscall(procOROpenHive.Addr(), 2, uintptr(unsafe.Pointer(hivePath)), uintptr(unsafe.Pointer(result)), 0)
if r0 != 0 {
win32err = syscall.Errno(r0)
}
return
}
func OROpenKey(handle ORHKey, subKey string, result *ORHKey) (win32err error) {
var _p0 *uint16
_p0, win32err = syscall.UTF16PtrFromString(subKey)
if win32err != nil {
return
}
return _OROpenKey(handle, _p0, result)
}
func _OROpenKey(handle ORHKey, subKey *uint16, result *ORHKey) (win32err error) {
r0, _, _ := syscall.Syscall(procOROpenKey.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(subKey)), uintptr(unsafe.Pointer(result)))
if r0 != 0 {
win32err = syscall.Errno(r0)
}
return
}
func ORSaveHive(handle ORHKey, hivePath string, osMajorVersion uint32, osMinorVersion uint32) (win32err error) {
var _p0 *uint16
_p0, win32err = syscall.UTF16PtrFromString(hivePath)
if win32err != nil {
return
}
return _ORSaveHive(handle, _p0, osMajorVersion, osMinorVersion)
}
func _ORSaveHive(handle ORHKey, hivePath *uint16, osMajorVersion uint32, osMinorVersion uint32) (win32err error) {
r0, _, _ := syscall.Syscall6(procORSaveHive.Addr(), 4, uintptr(handle), uintptr(unsafe.Pointer(hivePath)), uintptr(osMajorVersion), uintptr(osMinorVersion), 0, 0)
if r0 != 0 {
win32err = syscall.Errno(r0)
}
return
}
func ORSetValue(handle ORHKey, valueName string, valueType uint32, data *byte, dataLen uint32) (win32err error) {
var _p0 *uint16
_p0, win32err = syscall.UTF16PtrFromString(valueName)
if win32err != nil {
return
}
return _ORSetValue(handle, _p0, valueType, data, dataLen)
}
func _ORSetValue(handle ORHKey, valueName *uint16, valueType uint32, data *byte, dataLen uint32) (win32err error) {
r0, _, _ := syscall.Syscall6(procORSetValue.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(valueName)), uintptr(valueType), uintptr(unsafe.Pointer(data)), uintptr(dataLen), 0)
if r0 != 0 {
win32err = syscall.Errno(r0)
}
return
}